Option-1: Using CSS class already provided:
Every widget already provides unique id
and class
to use in CSS rules. So for most styling needs, it's better to use those to generate specific CSS rule that'll only work for that widget (e.g. Search). For example, the default Search widget will have the CSS class widget_search
. You may use it to style the search widget differently from other widgets. Like:
.widget {
background-color: wheat;
}
.widget.widget_search {
background-color: gold;
}
Option-2: Using dynamic_sidebar_params
filter:
Since you are registering the widgets with register_sidebar()
function, most likely you've used it with dynamic_sidebar()
function in the templates. In that case, you may use the dynamic_sidebar_params
filter hook to insert extra CSS classes only to a specific widget.
Use the following CODE in your theme's functions.php
file (additional instructions are there in the CODE):
add_filter( 'dynamic_sidebar_params', 'wpse258279_filter_widget' );
function wpse258279_filter_widget( $params ) {
// avoiding admin panel
if( ! is_admin() ) {
if ( is_array( $params ) && is_array( $params[0] ) && $params[0]['widget_name'] === 'Search' ) {
// Insert your custom CSS class (one or more) in the following array
$classes = array( 'custom-css-class-for-search' );
// The following three lines will add $classes
// (along with the existing CSS classes) using regular expression
// don't touch it if you don't know RegEx
$pattern = '/class\s*=\s*(["\'])(?:\s*((?!\1).*?)\s*)?\1/i';
$replace = 'class=$1$2 ' . implode( ' ', $classes ) . '$1';
$params[0]['before_widget'] = preg_replace( $pattern, $replace, $params[0]['before_widget'], 1 );
}
}
return $params;
}
With the above CODE, you may add one or more CSS classes in this line: $classes = array( 'custom-css-class-for-search' );
. So if you want to add two CSS classes for the search widget, it'll be like:
$classes = array( 'custom-css-class-for-search', 'another-class' );
Option-3: Custom Widget:
If you need more control than the above methods can handle, then you may implement custom Widget for Search like shown in this answer.
However, it may be difficult to maintain custom widgets if you want the same behaviour for multiple widgets. Because then you'll have to implement that widget too (only for extra CSS class)! If that's not an issue for you, then you may follow that path, as with a custom Widget, you'll have far better control over the markups and functionality.
Option-2
from my answer?