首页 > 解决方案 > 如何在不打印的情况下获取 Wordpress 小部件(侧边栏)?

问题描述

我正在使用 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 中是否还有另一个功能可以做同样的事情?

标签: phpwordpress

解决方案


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

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;

推荐阅读