Add div class to only one widget

You have two possible solutions.

1. The widget_display_callback filter hook

This filter hook parameters allows you to target easily the widget instance and override it’s arguments.

A possible approach would be: Inside the filter callback, modify the arguments for that instance, display it and then return false to prevent it from being displayed again the normal way by WordPress. See this code in wp-includes/class-wp-widget.php.

2. Register a new widget that extends the search widget

You can extend the search widget –defined in wp-includes/widgets/class-wp-widget-search.php and override the widget() method to add the class you want, something like this (code should be added in some place seen by WordPress, like a custom plugin or in your theme functions.php file):

/**
 * Custom widget search
 *
 * Extends the default search widget and adds a class to classes in `before_title`
 *
 * @author  Nabil Kadimi
 * @link    http://wordpress.stackexchange.com/a/258292/17187
 */
class WP_Widget_Search_Custom extends WP_Widget_Search {

    public function __construct() {
        $widget_ops = array(
            'classname' => 'widget_search widget_search_custom',
            'description' => __( 'A Custom search form for your site.' ),
            'customize_selective_refresh' => true,
        );
        WP_Widget::__construct( 'search_custom', _x( 'Custom Search', 'Custom Search widget' ), $widget_ops );
    }

    public function widget( $args, $instance ) {

        $custom_class="wpse-258279";
        $args['before_widget'] = str_replace('class="', "class=\"$custom_class", $args['before_widget']);

        /** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
        $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );
        echo $args['before_widget'];
        if ( $title ) {
            echo $args['before_title'] . $title . $args['after_title'];
        }
        // Use current theme search form if it exists
        get_search_form();
        echo $args['after_widget'];
    }
}

/**
 * Register the custom search widget
 */
add_action( 'widgets_init', function() {
    register_widget( 'WP_Widget_Search_Custom' );
} );

Leave a Comment