0

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?

  • Shouldn't you be using 'pa_ingredients' => $term->slug ? – Sally CJ Jul 21 at 8:02
  • 1
    That's absolutely true, @SallyCJ -- altering that corrected it 😀 – Ash Jul 21 at 8:08
0

Error in wc_get_products caught by @SallyCJ fixed my problem.

Where I had ingredients, I needed pa_ingredients.

Working code is as follows:

$taxonomy = 'pa_ingredients';
$terms = get_terms( $taxonomy );
foreach ( $terms as $term ) {
    $products = wc_get_products( array( 'pa_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>';
    }
}

Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.