开发者问题收集

无法获取类别产品 Woocommerce

2018-11-29
275

我正在运行下一个代码:

确定类别页面的类别 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,但输出很清楚: 在此处输入图片说明

2个回答

他们在这里说

[ 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;
}
Thorene
2018-11-29

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

$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
        );
Artem Kopytko
2018-11-30