Adding a Class to a Wordpress Widget

Adding a Class to a Wordpress Widget

Recently on a project I came across an issue whereby a widget had no specific id or class in which I could use to style the content. Below is a piece of code you can use to target a individual widget and add a class to the widget.

function cm_add_widget_class( $params ) {
	
	// Setup the Variables 
	$name = $params[0]['widget_name'];
	$widgetName = 'Better RSS Widget';
	$widgetClass = 'mywidgetclass ';

	// If it is the Widget add the Class to the Widget 
	if($name == $widgetName ) {
		$params[0]['before_widget'] = preg_replace( '/class="/', "class="" .$widgetClass . ' ' . "", $params[0]['before_widget'], 1 );
	}
	return $params;
}
add_filter( 'dynamic_sidebar_params', 'cm_add_widget_class' );
Tags:
css.php