【问题标题】:How to get Wordpress Widget(sidebar) without printing it?如何在不打印的情况下获取 Wordpress 小部件(侧边栏)?
【发布时间】:2020-03-03 02:17:55
【问题描述】:

我正在使用 Wordpress 和 PHP。我使用此代码声明了一个自定义侧边栏:

   function customtheme_widgets_init() {
register_sidebar( array(
  'name'          => esc_html__( 'My custom sidebar', 'customtheme' ),
  'id'            => 'my-custom-sidebar',
  'description'   => esc_html__( '.', 'customtheme' ),
  'before_widget' => '',
  'after_widget'  => '',
  'before_title'  => '',
  'after_title'   => '',
) );
}
add_action( 'widgets_init', 'customtheme_widgets_init' );

好的,所以在我的代码中,我想获取侧边栏并将其存储在 PHP 变量 $the_widget 中。使用此代码:

if ( is_active_sidebar( 'my-custom-sidebar' ) ) :
    $the_widget = dynamic_sidebar('my-custom-sidebar');
endif;

当我这样做时,它会在我调用 dynamic_sidebar() 时自动回显小部件(侧边栏),我可以在没有回显的情况下做到这一点吗? wordpress codex 中是否还有其他功能可以做到这一点?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    不幸的是,没有像 get_dynamic_sidebar() 这样的 WordPress 函数,但是将侧边栏作为字符串放入变量的常用方法是:

    if ( is_active_sidebar( 'my-custom-sidebar' ) ) :
        ob_start();
        dynamic_sidebar('my-custom-sidebar');
        $the_widget = ob_get_contents();  //or ob_get_clean();
        ob_end_clean();
    endif;
    

    【讨论】:

    • 太棒了!很高兴我能帮上忙! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 2014-09-02
    • 2014-08-28
    • 2010-11-26
    相关资源
    最近更新 更多