1. Home
  2. /
  3. Web Design & Development
  4. /
  5. WordPress
  6. /
  7. Add Custom Class to WordPress Widgets

Add Custom Class to WordPress Widgets

Add Custom Class to WordPress Widgets

Sometimes we come across situations where we are in a desperate need to add custom classes to the WordPress widget specifically to the individual elements to meet some specific design or functionality requirements.

I was facing the same issue and ended up spending hours in searching for a feasible solution. And, after going through so many online articles and posts and spending hours.. I came across a solution that I thought to share and create a summarized post that might help saving your time and efforts.

Register a WordPress Widget

Add the following piece of code to your plugin or theme functions.php file.

if ( function_exists('register_sidebar') ) {

    $mySidebar = array(
        'id'            => 'yourUniqueSidebarId',
        'before_widget' => '<div class="widget %2$s">',
        'after_widget' => '</div>',
        'before_title' => '<h2 class="widget_title">',
        'after_title' => '</h2>',        
        'name'=>__( 'Your Sidebar Name', 'textdomain' ),  
    register_sidebar( $mySidebar );


Add Custom Class To Your Widget Element

Adjust your conditional checks as per need. You can check and apply it for all “Image” widget elements or further restrict to a specific sidebar widget using sidebar id.


add_filter( 'dynamic_sidebar_params', 'my_add_widget_class' );

function my_add_widget_class( $params ) {
    if(!empty($params) && $params[0]['widget_name']=='Image' && $params[0]['id']=='yourUniqueSidebarId'){ 
       $params[0] = array_replace($params[0], array('before_widget' => str_replace("widget_media_image", "widget_media_image sg-footer-ter", $params[0]['before_widget'])));


      return $params;


Place this script in your functions.php file

This is tested code and I hope it helps you as well. Good luck.

Reviews & Ratings Get your stoe online with Shopify in 60 minutes Shop Now