How do I change the product loop parameters in Woocommerce archive page?

10,870

Solution 1

Woocommerce simply relies on wordpress global $wp_query, you can use pre_get_posts action hook to modify any query,

e.g.

function _additional_woo_query( $query ) {
    if ( is_product_category() ) {
        $query->set( 'cat', '123' );
    }
}
add_action( 'pre_get_posts', '_additional_woo_query' );

checkout woocommerce conditional tag

Solution 2

Try the following code.
Paste it in functions.php of your theme.
Replace $product_category_id with your value.

function _new_updated_query( $query ) {
if ( is_product_category() && $query->is_main_query() ) {
    $query->set( 'tax_query', array (
        array(
          'taxonomy' => 'product_cat',
          'field'    => 'term_id',
          'terms'    => absint($product_category_id),
        )
    ));
}
}
add_action( 'pre_get_posts', '_new_updated_query' );
Share:
10,870

Related videos on Youtube

Victor Ferreira
Author by

Victor Ferreira

Web developer, majored in Information Systems and Informatics, now learning how to program for Android. In love with flat design.

Updated on September 24, 2022

Comments

  • Victor Ferreira
    Victor Ferreira over 1 year

    Well I'm trying to create some custom loop pages for Woocommerce products, and I found out that the process starts in archive-product.php file and then it include template snippets to draw the page.

    But I want to change the parameters to be queried, so it will join some product categories, or will exclude some products or some categories from the loop (just like we do in category.php in a Wordpress project).

    How do I do it?! Where can I find this part of the script?

    Thanks!

  • Warface
    Warface almost 4 years
    Adding this in the 'pre_get_posts' will mess up all the global queries for other stuff like the navigation and other loops
  • silver
    silver almost 4 years
    thats why you need a condition on where to inject it and only modify the specific query you want