[英]How to get Wordpress Widget(sidebar) without printing it?
我正在使用 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 中是否有另一个功能可以做同样的事情?
不幸的是,没有像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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.