php - 如何在不打印的情况下获取 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 中是否还有另一个功能可以做同样的事情?
解决方案
不,不幸的是没有 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;
推荐阅读
- docker - 从私有 GKE 集群访问非 gcr 公共容器注册表
- python - 通过传递参数使用python的psycopg2运行sql文件
- excel - 如何在 Excel 电源查询中查找两个单独查询的位置之间的距离?
- javascript - 添加了返回承诺,但随后不执行
- javascript - 使用蹦床编写阿克曼函数
- javascript - 构建确认网关功能
- python - 计算每个品牌的客户数量
- arrays - Kotin 类型不匹配:推断类型是 Int?但预计 Int
- c# - ListBox 中的 WPF 复选框:内容绑定未正确更新(即使已实现 INotifyPropertyChanged)
- google-apps-script - 使用 .getBackgrounds() 将背景颜色复制到范围