WooCommerce-获取产品页面类别 [英] WooCommerce - get category for product page

查看:84
本文介绍了WooCommerce-获取产品页面类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的WC产品页面,我需要向body标签添加一个类,以便可以执行一些自定义样式.这是我为此创建的功能...

For my WC product pages, I need to add a class to the body tag so that I can perform some custom styling. Here's the function I'm creating for this...

function my_add_woo_cat_class($classes) {

    $wooCatIdForThisProduct = "?????"; //help!

    // add 'class-name' to the $classes array
    $classes[] = 'my-woo-cat-id-' . $wooCatIdForThisProduct;
    // return the $classes array
    return $classes;
}

//If we're showing a WC product page
if (is_product()) {
    // Add specific CSS class by filter
    add_filter('body_class','my_add_woo_cat_class');
}

...但是如何获取WooCommerce猫的ID?

...but how do I get the WooCommerce cat ID?

推荐答案

WC产品可能不属于一个或多个WC类别.假设您只想获取一个WC类别ID.

A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
    $product_cat_id = $term->term_id;
    break;
}

请查看WooCommerce插件的"templates/single-product/"文件夹中的meta.php文件.

Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.

<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>

这篇关于WooCommerce-获取产品页面类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆