有没有办法通过拥有ID来打印小部件?

时间:2021-07-31 作者:Paolo Battiloro

我在wp中有一个自定义侧栏,由以下人员创建:

register_sidebar(array(
    \'id\' => \'test_w\',
    \'name\' => \'test\',
    \'before_widget\' => \'<div class = "widgetizedArea">\',
    \'after_widget\' => \'</div>\',
    \'before_title\' => \'<h3>\',
    \'after_title\' => \'</h3>\',
));
现在,我用代码打印内部小部件的ID:

 $nomi_widget = array();
 $sidebars_widgets = wp_get_sidebars_widgets();
 var_dump($sidebars_widgets[\'test_w\']);       
输出为:

array (size=2)
  0 => string \'adni_widgets-93\' (length=15)
  1 => string \'adni_widgets-96\' (length=15)
问题是:有没有一种方法可以使用其ID在前端打印小部件?

1 个回复
最合适的回答,由SO网友:majick 整理而成

一种方法是在调用dynamic_sidebar 输出

Updated to take widget index OR ID slug

function custom_output_widget( $sidebar_id, $widget_id ) {
    global $custom_widget_target; 
    // if ( !$sidebar_id ) {
    //     $sidebars_widgets = get_option( \'sidebars_widgets\' );
    //     print_r( $sidebars_widgets ); return;
    // }
    $custom_widget_target = array( \'sidebar\' => $sidebar_id, \'widget\' => $widget_id );
    add_filter( \'sidebars_widgets\', \'custom_widget_target_filter\' );
    dynamic_sidebar( $sidebar_id );
    remove_filter( \'sidebars_widgets\', \'custom_widget_target_filter\' );
    unset( $custom_widget_target );
}

function custom_widget_target_filter( $sidebars ) {
    global $custom_widget_target;
    if ( isset( $custom_widget_target) ) {
        foreach ( $sidebars as $sidebar_id => $widgets ) {
            if ( ( count( $widgets ) > 0 ) && ( $sidebar_id == $custom_widget_target[\'sidebar\'] ) ) {
                foreach ( $widgets as $i => $widget ) {
                    // echo \'*\' . $i . \' - \' . $widget . \'*\';
                    if ( ( $widget !== $custom_widget_target[\'widget\'] ) && ( $i !== $custom_widget_target[\'widget\'] ) ) {
                        unset( $widgets[$i] );
                    }
                }
            }
            $sidebars[$sidebar_id] = $widgets;
        }
    }
    return $sidebars;
}

// example based on widgets in original question
custom_output_widget( \'test_w\', \'adni_widgets-93\' );

Updated and simplified with closure (takes widget slug:)

function display_widget_wpse( $s_id, $w_id ) {
  add_filter( \'sidebars_widgets\', $callback = function( $widgets ) use ($s_id, $w_id) {
    return array ( $s_id => array_filter ( 
      $widgets[$s_id] ?? array(), 
      function ( $widget ) use ( $w_id ) { return $w_id === $widget; } 
     ) );
  } );
  dynamic_sidebar( $s_id );
  remove_filter( \'sidebars_widgets\', $callback );
}

相关推荐

My widgets do not save

每次我保存我的小部件并离开页面时,我的小部件都会消失。侧边栏已完全清空,不会保存任何更改。控制台或PHP日志中没有任何错误。如果我将小部件直接复制并保存在数据库中widgets_text, 它们将被显示,但我仍然无法在侧边栏中添加或删除任何内容。这只发生在我的右侧边栏上,左侧边栏工作正常,但它们都以相同的方式注册。这是我注册侧边栏的方式:function my_widgets_init() { register_sidebar( array ( \'name\'