Checking If A WordPress Widget Displayed In The Cu

2019-09-12 15:28发布

问题:

Is there a function to check if a widget is displayed in the current front end?
This is necessary for pulling some styles or scripts or doing other action to the widget.

回答1:

Please see if this works by echoing the contents $GLOBALS['displayed_sidebars'] and $GLOBALS['displayed_widgets'], using print_r for example.

It must be tested after dynamic_sidebar has been executed for all sidebars that you want to include.

add_filter( 'dynamic_sidebar_params', function( $params ) {
    global $displayed_sidebars, $displayed_widgets;
    if( !in_array( $params[0]['id'], $displayed_sidebars ))
        $displayed_sidebars[] = $params[0]['id'];

    if( !in_array( $params[0]['widget_name'], $displayed_widgets ))
        $displayed_widgets[] = $params[0]['widget_name'];

    return $params;
});


标签: wordpress