I'm currently building a glossary page listing a specific product attribute, and would like to link to each of the products associated with each term for that attribute.
I believe I should be using wc_get_products with a custom filter, but can only get it to display all products, regardless of associated attribute terms.
Following is the custom filter I have in place:
function my_handle_custom_query_var( $query, $query_vars ) {
if ( !empty( $query_vars['pa_ingredients'] ) ) {
$query[ 'tax_query' ][] = array(
'taxonomy' => 'pa_ingredients',
'field' => 'slug',
'terms' => $query_vars['pa_ingredients'],
'operator' => 'IN',
);
}
return $query;
}
add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'my_handle_custom_query_var', 10, 2 );
And following is the code I'm using to display the associated products:
$taxonomy = 'pa_ingredients';
$terms = get_terms( $taxonomy );
foreach ( $terms as $term ) {
$products = wc_get_products( array( 'ingredients' => $term->slug ) );
foreach ( $products as $product ) {
$product_id = wc_get_product_id_by_sku( $product->sku );
$link = get_permalink( $product_id );
echo '<a href="' . $link . '">' . $product->name . '</a>';
}
}
Any ideas what I'm doing wrong?
'pa_ingredients' => $term->slug
? – Sally CJ Jul 21 '19 at 8:02