M
M
Michael R.2020-04-29 11:06:03
WordPress
Michael R., 2020-04-29 11:06:03

Individual class for each of the widgets in a WordPress sidebar?

Greetings!

How can I set an additional individual class for a widget wrapper from the WP admin?

The option to change the widget structure so that this "wrapping" is generated at the widget level is not suitable, because in this case, you will have to redo all the widgets by hand (for a long time, and if the widget is updated, redo it again?), and in different sidebars there can be different types of wrappers for the displayed widgets... I

register a sidebar with a wrapper for each of the widgets that will be displayed within this sidebar:

register_sidebar([
      "id" => "test id",
      "name" => "test name",
      "description" => "test desc",
      "before_widget" => '<li id="%1$s" class="wp_widget_wrap %2$s">',
      "after_widget" => "</li>",
      "before_title" => '<h3 class="wp_widget_title">',
      "after_title" => "</h3>",
  ]);


Then I create the widget:
class test_widget extends WP_Widget {
  function __construct() {
    parent::__construct("test_class_widget", "Заголовок виджета", [
            "classname" => "test_class_widget",
            "description" => "test desc widget",
        ]);
  }



  public function widget($args, $instance) {
    $title = apply_filters('widget_title', $instance['title']);
    echo $args['before_widget'] . $args['before_title'] . $title . $args['after_title']; ?>
    <p class="<? echo $instance["class"] ?>"><strong>Site Name:</strong></p>
    <?php echo $args['after_widget'];
  }



  public function form($instance) {
    $title = !empty($instance['title']) ? $instance['title'] : '';
    $class = !empty($instance['class']) ? $instance['class'] : '';
    
    // поля для указание title и css класса
    ?>

    <p>
      <label for="<?php echo $this->get_field_id('title'); ?>">Title:</label>
      <input
          type="text"
          id="<?php echo $this->get_field_id('title'); ?>"
          name="<?php echo $this->get_field_name('title'); ?>"
          value="<?php echo esc_attr($title); ?>"
      />
    </p>

    <p>
      <label for="<?php echo $this->get_field_id('class'); ?>">CSS class:</label>
      <input
          type="text"
          id="<?php echo $this->get_field_id('class'); ?>"
          name="<?php echo $this->get_field_name('class'); ?>"
          value="<?php echo esc_attr($class); ?>"
      />
    </p>
    <?php
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question