只有在 function so_32165017_conditionally_remove_sidebar
中,如果条件触发意味着删除操作删除侧边栏时,我才尝试添加主体类 add_filter( 'body_class ', 'my_class_names' );
这个添加过滤器应该被触发,但在我的情况下,如果我将 add_filter 语句添加为独立的,那么如果我在 if 条件下添加相同的语句则工作正常,但它不是,我哪里出错了不确定,。
function so_32165017_get_product_cat_depth($catid)
{
$depth = 0;
while ($catid) {
$cat = get_term_by('id', $catid, 'product_cat'); // get the object for the catid
if ($cat->parent > 0) {
$depth++;
}
$catid = $cat->parent; // assign parent ID (if exists) to $catid
// the while loop will continue whilst there is a $catid
}
return $depth;
}
add_action('woocommerce_before_main_content', 'so_32165017_conditionally_remove_sidebar');
/**
* Hide the sidebar for items 2 levels deep or more
*/
function so_32165017_conditionally_remove_sidebar()
{
if (is_product_category()) {
$t_id = get_queried_object()->term_id;
if (so_32165017_get_product_cat_depth($t_id) < 2) {
remove_action('storefront_sidebar', 'storefront_get_sidebar', 10);
// ****when added hear it is not working ****??//
add_filter('body_class', 'my_class_names');
}
}
}
添加类代码:
// **** works fine hear ****//
add_filter( 'body_class', 'my_class_names' );
function my_class_names( $classes ) {
// add 'class-name' to the $classes array
$classes[] = 'My-Class';
// return the $classes array
return $classes;
}
最佳答案
您需要的是单独调用您的操作。您的操作 woocommerce_before_main_content
在正文类之后运行,因此在操作之后添加过滤器将不起作用。
add_action('woocommerce_before_main_content', 'so_32165017_conditionally_remove_sidebar');
function so_32165017_conditionally_remove_sidebar()
{
if (is_product_category()) {
$t_id = get_queried_object()->term_id;
if (so_32165017_get_product_cat_depth($t_id) < 2) {
remove_action('storefront_sidebar', 'storefront_get_sidebar', 10);
}
}
}
add_filter('body_class', 'my_class_names',10,2);
function my_class_names( $classes ) {
if (is_product_category()) {
$t_id = get_queried_object()->term_id;
if (so_32165017_get_product_cat_depth($t_id) < 2) {
$classes[] = 'My-Class';
}
}
// return the $classes array
return $classes;
}
关于php - WordPress 在 if 条件下触发 Action 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32547513/