无法获得类别产品Woocommerce

时间:2018-11-29 21:48:50

标签: php wordpress woocommerce

我正在运行下一个代码:

确定类别页面的类别ID

<?php
        $cat_id = get_queried_object_id();
        echo 'cat_id = ' . $cat_id;?>

试图获得此类产品:

$args = array(
            'post_type' => 'product',
            'posts_per_page' => 12,
            'cat' => $cat_id
        );

        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>

            <div class="product <?php echo the_title(); ?>" data-profile="<?php echo $loop->post->ID; ?>">
                <?php $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $loop->post->ID ), 'single-post-thumbnail' ); ?>
                <?php if($featured_image) { ?>
                    <div class="product-image" style="background-image: url('<?php echo $featured_image[0]; ?>')">
                        <a href="<?php echo $product->get_permalink();?>"></a>
                    </div>
                <?php } ?>

                <a href="<?php echo $product->get_permalink();?>"><?php the_title(); ?></a>




                <p><? echo $product->term_id; ?></p>
                <?php if ($average = $product->get_average_rating()) : ?>
                    <?php echo '<div class="star-rating" title="'.sprintf(__( 'Рейтинг %s из 5', 'woocommerce' ), $average).'"><span style="width:'.( ( $average / 5 ) * 100 ) . '%"><strong itemprop="ratingValue" class="rating">'.$average.'</strong> '.__( 'из 5', 'woocommerce' ).'</span></div>'; ?>
                <?php endif; ?>

                <span class="price"><?php echo $product->get_price_html(); ?></span>

                <?php

                global $wp_query;
                $terms_post = get_the_terms( $post->cat_ID , 'product_cat' );
                foreach ($terms_post as $term_cat) {
                    $term_cat_id = $term_cat->term_id;
                    echo 'My category id: ' . $term_cat_id;
                }

                ?>
            </div>
        <?php endwhile; ?>

这什么也不显示。我在获取所有类别的同时检查了产品类别。 cat_id = 15,product_cat_id = 15,但输出清晰: enter image description here

2 个答案:

答案 0 :(得分:1)

他们在这里说

[https://wordpress.stackexchange.com/questions/150031/retrieve-product-category-name-by-product-category-id-woocommerce][1]

您可以使用get_term_by()

$id = 42;
if( $term = get_term_by( 'id', $id, 'product_cat' ) ){
    echo $term->name;
}

答案 1 :(得分:0)

要获取该类别的产品(在类别页面上)

$cat_id = get_queried_object_id();

        $term = get_term( $cat_id, 'product_cat' );
        $slug = $term->slug;

        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 12,
            'product_cat' => $slug
        );