这个函数挂接在哪里?
widgets_init 连接到init 优先考虑1, 但WooCommerce在init 优先考虑5. 所以如果你使用widgets_init 作为你无法使用的钩子get_terms() 因为它返回WP_Error 如果分类法未注册。
您需要在上注册小部件init 优先级大于5 要使其工作,您仍应检查get_terms() 不是一个WP_Error, 如果WooCommerce未激活:
function wpse_295558_category_sidebars() {
$product_cats = get_terms( array(
\'taxonomy\' => \'product_cat\',
\'hide_empty\' => false,
\'parent\' => 0,
);
if ( ! is_wp_error( $product_cats ) ) {
foreach ( $product_cats as $product_cat ) {
register_sidebar( array(
\'name\' => \'Filter sidebar -\' . $product_cat->name,
\'id\' => \'filter_sidebar_\' . $product_cat->name,
\'before_widget\' => \'<div class="filter-sidebar-\' . $product_cat->name . \'">\',
\'after_widget\' => \'</div>\',
\'before_title\' => \'<h2 class="filter-title">\',
\'after_title\' => \'</h2>\',
) );
}
}
}
add_action( \'init\', \'wpse_295558_category_sidebars\', 10 );
不过,这似乎是一种难以实现的方法。为类别设置一个侧栏,然后让小部件动态响应您正在查看的类别,不是更好吗?这已经是WooCommerce中捆绑过滤器小部件的工作方式。