WooCommerce - 获取产品页面的类别

ban*_*ing 34 php wordpress woocommerce

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

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');
}
Run Code Online (Sandbox Code Playgroud)

...但是如何获得WooCommerce猫咪ID?

Box*_*Box 70

WC产品可以属于无,一个或多个WC类别.假设您只想获得一个WC类别ID.

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

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

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


Jay*_*vat 11

$product->get_categories()自 3.0 版起已弃用!使用wc_get_product_category_list来代替。

https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html


Alr*_*eed 6

我从主题目录中woocommerce文件夹中的content-single-popup.php中逐行删除了这行代码。

global $product; 
echo $product->get_categories( ', ', ' ' . _n( ' ', '  ', $cat_count, 'woocommerce' ) . ' ', ' ' );
Run Code Online (Sandbox Code Playgroud)

由于我正在研究的主题已将woocommerce集成到其中,因此这就是我的解决方案。


小智 5

谢谢盒子。我正在使用 MyStile 主题,我需要在我的搜索结果页面中显示产品类别名称。我将此功能添加到我的子主题functions.php

希望它可以帮助其他人。

/* Post Meta */


if (!function_exists( 'woo_post_meta')) {
    function woo_post_meta( ) {
        global $woo_options;
        global $post;

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

?>
<aside class="post-meta">
    <ul>
        <li class="post-category">
            <?php the_category( ', ', $post->ID) ?>
                        <?php echo $product_cat; ?>

        </li>
        <?php the_tags( '<li class="tags">', ', ', '</li>' ); ?>
        <?php if ( isset( $woo_options['woo_post_content'] ) && $woo_options['woo_post_content'] == 'excerpt' ) { ?>
            <li class="comments"><?php comments_popup_link( __( 'Leave a comment', 'woothemes' ), __( '1 Comment', 'woothemes' ), __( '% Comments', 'woothemes' ) ); ?></li>
        <?php } ?>
        <?php edit_post_link( __( 'Edit', 'woothemes' ), '<li class="edit">', '</li>' ); ?>
    </ul>
</aside>
<?php
    }
}


?>
Run Code Online (Sandbox Code Playgroud)