php - WordPress 在 if 条件下触发 Action 过滤器

标签 php wordpress

只有在 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/

相关文章:

php - 在 codeigniter 中找不到请求的 url 错误

javascript - 如何将 jquery ui 自动完成小部件与数据库连接?

mysql - 在我的 WordPress 文件不在根 FTP 文件夹中时使用 MySQL

wordpress - wordpress管理面板504网关超时类别

php - 使用 PHP 从具有多个条目的多个表中查询 MySQL 数据

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - 按子数组的长度对数组数组进行排序?

php - 如何从 Woocommerce 面包屑中删除 "Home"链接?

php - Wordpress 开发人员自定义背景选项

wordpress - 如何在 Wordpress 中创建自定义用户角色