【问题标题】:Add a body class related to the product category in WooCommerce在 WooCommerce 中添加与产品类别相关的正文类
【发布时间】:2016-05-16 15:04:00
【问题描述】:

如何添加与产品类别 slug 相关的 body 类?

谢谢!

【问题讨论】:

标签: php wordpress woocommerce wordpress-theming categories


【解决方案1】:

将此添加到您的functions.php

add_filter( 'body_class', 'wc_cat_names' );
function wc_cat_names( $classes ) {
    if(is_product()){
    global $post;
    $terms = get_the_terms( $post->ID, 'product_cat' );
        foreach ($terms as $term) {
            $classes[] = $term->slug;
        }
    }
    return $classes;
}

这个仅适用于 woocommerce 产品页面,是的,我在我的测试网站上测试了它。

【讨论】:

    【解决方案2】:

    在 Wordpress 支持网站上有一个很好的指南:Modify body_class() output to show category-{slug} for single posts

    我已更改帖子中的代码以满足您的需求:

    add_filter('body_class','add_category_to_single');
    function add_category_to_single($classes, $class) {
        if (is_single() ) {
            global $post;
            foreach((get_the_category($post->ID)) as $category) {
                echo $category->cat_name . ' ';
                // add category slug to the $classes array
                $classes[] = $category->slug;
            }
        }
        // return the $classes array
        return $classes;
    }
    

    【讨论】:

    • 老实说不,不是在回答的时候。我在早期的项目中使用了它的修改版本,这就是我记得这篇文章的原因。
    • 但是根据Wordpress Codex: body_class,它应该仍然是一个有效的钩子。
    • 这给了我一个 php 错误并将 body_class 添加到另一个 div。错误:Warning: Missing argument 2 for add_category_to_single(
    • 是的,这个钩子很好,是一个经典的钩子,没问题……但是 woocommerce 类别与 wordpress 的类别有点不同……别担心,只是问:)
    • 这是您的想法……但正如我所说,未经测试。太多reputation机会主义,对不起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多