Gaël
Gaël

Reputation: 13

Filter Woocommerce archive pages with product attribute values by default

I would like products archive pages to display products corresponding to a specific attribute value by default.

Example
Attribute: pa_condition
Terms: New, Used, Closeout

I would like to see only new products when opening the shop.

But there are 2 languages. So I guess, the condition should apply to the attribute id.

How this can be done?

Upvotes: 1

Views: 2051

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253901

Updated: You can try this hooked function:

add_filter( 'woocommerce_product_query_tax_query', 'custom_product_query_tax_query', 10, 2 );
function custom_product_query_tax_query( $tax_query, $query ) {
    if( is_admin() ) return $tax_query;

    // Define HERE the product attribute and the terms
    $taxonomy = 'pa_condition';
    $terms = array( 'New', 'Used', 'Closeout' ); // Term names

    // Add your criteria
    $tax_query[] = array(
        'taxonomy' => $taxonomy,
        'field'    => 'name', // Or 'slug' or 'term_id'
        'terms'    => $terms,
    );
    return $tax_query;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.

But I am not sure about the translations of the terms, so you should be oblige to add them in a second $tax_query[] array in the query for that translated terms…


Official reference: WP_Query ~ Taxonomy Parameters

Upvotes: 1

Related Questions