Find if widget block is active

Question

I’m used to check if a widget from installed my plugin is active.

With the new block editor extending to widgets in WordPress 5.8, I was wondering if there is a way to check the widget block that I created (both old php-based and gutenberg-based widgets are installed by my plugin) is activated by the user.

Thanks!

in progress 0
JCV 2 months 2021-07-26T16:56:25-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-08-01T10:15:36-05:00

    One could e.g. get the widget blocks data with:

    $widget_blocks = get_option( 'widget_block' );
    

    and then loop through the array and run has_block() on the contant part, e.g. like (untested):

    function is_active_block_widget_wpse( $blockname )
        $widget_blocks = get_option( 'widget_block' );
        foreach( (array) $widget_blocks as $widget_block ) {
            if ( ! empty( $widget_block['content'] ) 
                 && has_block( $blockname, $widget_block['content'] ) 
            ) {
                return true;
            }
        }
        return false;
    }
    

    to find if a given blockname is an active widget:

    is_active_block_widget_wpse( 'my-plugin/my-block' )
    

    We note that this simple implementation assumes none inactive block widgets.

    Other helpful functions: wp_get_sidebars_widgets() and is_active_widget()

Leave an answer

Browse
Browse