How to get all products from current WooCommerce product category?

别来无恙 提交于 2021-01-28 20:32:58

问题


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.

I tried this:

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

I also tried:

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

回答1:


Updated

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).

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.

Documentation: WP_Query and Taxonomy Parameters



来源:https://stackoverflow.com/questions/63311004/how-to-get-all-products-from-current-woocommerce-product-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!