如何从当前的WooCommerce产品类别中获取所有产品? [英] How to get all products from current WooCommerce product category?

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

问题描述

自定义我的 archive-product.php .如何在自定义循环中仅显示特定类别中的产品?这个类似的问题,没有"解决我的问题.我尝试 single_cat_title()来基于 this获取当前类别问题,但出现错误.我认为我需要根据此文档,但我不断收到错误消息.

Customizing my archive-product.php. How can I show only products within a certain category in a custom loop? This similar question, didn't solve my problem. I tried single_cat_title() to get the current category based on this question but got an error. I think I need to use get_queried_object() based on this documentation but I keep getting errors.

我尝试过:

<?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, );

推荐答案

已更新

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

On product category archive pages, to get the current product category term you will use:

  • Wordpress function get_queried_object() (to get the WP_Term Oject).
  • or Wordpress function get_queried_object_id() (to get the term Id).

自WordPress 3.1开始,不推荐在WP_Query中直接使用分类法参数.相反,您将按照以下方式使用税收查询:

Using directly the taxonomy parameter in a WP_Query is deprecated since WordPress 3.1. Instead you will use a tax query as follow:

<?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;
?>

经过测试,可以正常工作.

Tested and works.

文档: WP_Query 和分类参数

Documentation: WP_Query and Taxonomy Parameters

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

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