繁体   English   中英

如何从当前 WooCommerce 产品类别中获取所有产品?

[英]How to get all products from current WooCommerce product category?

自定义我的archive-product.php 如何在自定义循环中仅显示特定类别中的产品? 这个类似的问题,并没有解决我的问题。 我尝试single_cat_title()根据问题获取当前类别,但出现错误。 我想我需要根据这个文档使用get_queried_object()但我不断收到错误。

我试过这个:

<?php 
$category = single_cat_title('', false); // this returns your current category ?>

<?php
// Setup your custom query
$args = array( 
    'post_type' => 'product', 
    'product_cat' => $category,
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>

    <?php the_post_thumbnail(); ?>
        <br>
<?php endwhile; wp_reset_query(); // Remember to reset ?>

我也试过:

`$term_name = get_queried_object()->name;`
    // Setup your custom query
    $args = array( 
        'post_type' => 'product', 
        'product_cat' => $term_name, );

更新

在产品类别存档页面上,要获取您将使用的当前产品类别术语:

自 WordPress 3.1 起,不推荐在 WP_Query 中直接使用分类参数。 相反,您将使用如下税务查询

<?php
// Get The queried object ( a WP_Term or a WP_Post Object)
$term = get_queried_object();

// To be sure that is a WP_Term Object to avoid errors
if( is_a($term, 'WP_Term') ) :

// Setup your custom query
$loop = new WP_Query( array(
    'post_type'      => 'product',
    'posts_per_page' => -1,
    'post_status'    => 'publish',
    'tax_query'      => array( array(
        'taxonomy' => 'product_cat', // The taxonomy name
        'field'    => 'term_id', // Type of field ('term_id', 'slug', 'name' or 'term_taxonomy_id')
        'terms'    => $term->term_id, // can be an integer, a string or an array
    ) ),
) );

if ( $loop->have_posts() ) :
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div style="margin:8px; text-align:center;">
    <a href="'.get_the_permalink().'">';
the_post_thumbnail();
the_title();
echo '</a></div>';
endwhile;
wp_reset_postdata(); // Remember to reset
endif; endif;
?>

测试和工作。

文档: WP_Query和分类参数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM