Using WordPress ‘dynamic_sidebar_before’ PHP action

The dynamic_sidebar_before WordPress PHP action fires before widgets are rendered in a dynamic sidebar.

Usage

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

function your_custom_function($index, $has_widgets) {
    // your custom code here
}

Parameters

  • $index (int|string) – Index, name, or ID of the dynamic sidebar.
  • $has_widgets (bool) – Whether the sidebar is populated with widgets. Default true.

More information

See WordPress Developer Resources: dynamic_sidebar_before

Note: The action also fires for empty sidebars, and on both the front end and back end, including the Inactive Widgets sidebar on the Widgets screen.

Examples

Add a custom message before the sidebar

Add a custom message before the sidebar if it has widgets:

add_action('dynamic_sidebar_before', 'add_custom_message', 10, 2);

function add_custom_message($index, $has_widgets) {
    if ($has_widgets) {
        echo '<p><strong>Welcome to our sidebar!</strong></p>';
    }
}

Display a specific message for an empty sidebar

Display a custom message when the sidebar is empty:

add_action('dynamic_sidebar_before', 'empty_sidebar_message', 10, 2);

function empty_sidebar_message($index, $has_widgets) {
    if (!$has_widgets) {
        echo '<p><em>This sidebar is empty. Please add some widgets.</em></p>';
    }
}

Add a custom class to the sidebar wrapper

Add a custom class to the sidebar wrapper based on the sidebar index:

add_action('dynamic_sidebar_before', 'add_sidebar_class', 10, 2);

function add_sidebar_class($index, $has_widgets) {
    echo '<div class="sidebar-' . esc_attr($index) . '">';
}

Display a login form before the sidebar

Display a login form before the sidebar only for logged-out users:

add_action('dynamic_sidebar_before', 'display_login_form', 10, 2);

function display_login_form($index, $has_widgets) {
    if (!is_user_logged_in()) {
        wp_login_form();
    }
}

Display a custom banner ad before the sidebar

Display a custom banner ad before the sidebar only if it has widgets:

add_action('dynamic_sidebar_before', 'display_banner_ad', 10, 2);

function display_banner_ad($index, $has_widgets) {
    if ($has_widgets) {
        echo '<div class="banner-ad">';
        echo '<img src="your-banner-ad-url.jpg" alt="Banner Ad">';
        echo '</div>';
    }
}