Using WordPress ‘dynamic_sidebar’ PHP action

The dynamic_sidebar WordPress PHP action fires before a widget’s display callback is called. This action occurs on both the front end and back end, including for widgets in the Inactive Widgets sidebar on the Widgets screen. It doesn’t fire for empty sidebars.

Usage

add_action('dynamic_sidebar', 'your_custom_function', 10, 2);

function your_custom_function($widget, $params) {
    // your custom code here

    return $widget;
}

Parameters

  • $widget (array) – An associative array of widget arguments.
  • $params (array) – An associative array of multi-widget arguments.

More information

See WordPress Developer Resources: dynamic_sidebar

Examples

Add a custom class to a widget

Add a custom CSS class to a specific widget by modifying the ‘classname’ parameter.

add_action('dynamic_sidebar', 'add_custom_class_to_widget', 10, 2);

function add_custom_class_to_widget($widget, $params) {
    if ($widget['id'] == 'your_widget_id') {
        $params['classname'] .= ' your-custom-class';
    }
    return $widget;
}

Modify widget title

Change the title of a specific widget.

add_action('dynamic_sidebar', 'modify_widget_title', 10, 2);

function modify_widget_title($widget, $params) {
    if ($widget['name'] == 'your_widget_name') {
        $widget['name'] = 'New Widget Title';
    }
    return $widget;
}

Display widget only on specific pages

Prevent a specific widget from displaying on certain pages.

add_action('dynamic_sidebar', 'display_widget_on_specific_pages', 10, 2);

function display_widget_on_specific_pages($widget, $params) {
    if ($widget['id'] == 'your_widget_id' && !is_page('your_page_slug')) {
        return false;
    }
    return $widget;
}

Add custom HTML before widget content

Insert custom HTML before the widget content.

add_action('dynamic_sidebar', 'add_html_before_widget', 10, 2);

function add_html_before_widget($widget, $params) {
    if ($widget['id'] == 'your_widget_id') {
        echo '<div class="custom-html">Your custom HTML here</div>';
    }
    return $widget;
}

Add custom HTML after widget content

Insert custom HTML after the widget content.

add_action('dynamic_sidebar', 'add_html_after_widget', 10, 2);

function add_html_after_widget($widget, $params) {
    if ($widget['id'] == 'your_widget_id') {
        echo '<div class="custom-html">Your custom HTML here</div>';
    }
    return $widget;
}