Using WordPress ‘dynamic_sidebar_after’ PHP action

The dynamic_sidebar_after WordPress PHP action fires after widgets are rendered in a dynamic sidebar.

Usage

add_action('dynamic_sidebar_after', '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 is true.

More information

See WordPress Developer Resources: dynamic_sidebar_after

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 after a specific sidebar

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

function add_custom_message($index, $has_widgets) {
  if ($index == 'sidebar-1' && $has_widgets) {
    echo '<p>**Thanks for visiting our sidebar!**</p>';
  }
}

Add custom CSS class to body for sidebars with widgets

add_filter('body_class', 'add_sidebar_body_class');

function add_sidebar_body_class($classes) {
  if (is_active_sidebar('sidebar-1')) {
    $classes[] = 'has-sidebar';
  }
  return $classes;
}

Display a message when no widgets are in the sidebar

add_action('dynamic_sidebar_after', 'display_no_widgets_message', 10, 2);

function display_no_widgets_message($index, $has_widgets) {
  if (!$has_widgets) {
    echo '<p>**No widgets are currently active in this sidebar.**</p>';
  }
}

Add a custom wrapper after a specific sidebar

add_action('dynamic_sidebar_after', 'add_custom_wrapper', 10, 2);

function add_custom_wrapper($index, $has_widgets) {
  if ($index == 'footer-sidebar') {
    echo '</div> <!-- Close custom wrapper -->';
  }
}

Add custom tracking code after all sidebars

add_action('dynamic_sidebar_after', 'add_tracking_code', 10, 2);

function add_tracking_code($index, $has_widgets) {
  if ($has_widgets) {
    echo '<!-- Custom tracking code goes here -->';
  }
}