Is there any way to print a widget by having its id?

Question

i have a custom sidebar in wp created by:

register_sidebar(array(
                'id' => 'test_w',
                'name' => 'test',
                'before_widget' => '<div class = "widgetizedArea">',
                'after_widget' => '</div>',
                'before_title' => '<h3>',
                'after_title' => '</h3>',
            )

now I print the IDs of the widgets inside with the code:

 $nomi_widget = array();
 $sidebars_widgets = wp_get_sidebars_widgets();
 var_dump($sidebars_widgets['test_w']);       

the output is:

array (size=2)
  0 => string 'adni_widgets-93' (length=15)
  1 => string 'adni_widgets-96' (length=15)

the question is: there is a way to print widget in frontend using his ID?

in progress 0
Paolo Battiloro 2 months 2021-07-31T12:18:38-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-08-01T07:43:21-05:00

    One way to do this would be to filter out all the other widgets in the sidebar while calling the dynamic_sidebar output.

    function custom_output_widget( $sidebar_id, $widget_id ) {
        global $target_widget_id;
        $target_widget_id = $widget_id;
        add_filter( 'sidebars_widgets', 'custom_widget_targeting' );
        dynamic_sidebar( $sidebar_id );
        remove_filter( 'sidebars_widgets', 'custom_widget_targeting' );
        unset( $target_widget_id );
    }
    
    function custom_widget_targeting( $widgets ) {
        global $target_widget_id;
        if ( isset( $target_widget_id ) && isset( $widgets[$target_widget_id] ) ) {
            foreach ( $widgets as $id => $widget ) {
                if ( $id != $target_widget_id ) {
                    unset( $widgets[$id] );
                }
            }
        }
        return $widgets;
    }
    
    custom_output_widget( 'test_w', 'adni_widgets-93' );

Leave an answer

Browse
Browse