-
AuthorPosts
-
October 14, 2024 at 4:00 pm #1469097
Good morning
I would like to show the related products of a certain category on the single product page.
Unfortunately your related products widget does not allow such a filter.
Is there a way, via CSS, to select a category in related products?October 15, 2024 at 5:35 am #1469120Hey fabio,
Thank you for the inquiry.
Related products are generated by WooCommerce, and there is no default option to change which items are shown in the grid. You can try the following filter in the functions.php file to change the related products query but this will affect the site globally.
add_filter( 'woocommerce_related_products', 'avf_custom_related_products_by_category', 10, 3 ); function avf_custom_related_products_by_category( $related_posts, $product_id, $args ) { $category_id = 123; // Replace 123 with your desired category ID $related_products = get_posts( array( 'posts_per_page' => $args['posts_per_page'], 'post_type' => 'product', 'fields' => 'ids', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $category_id, ), ), ) ); return $related_products; }
Make sure to replace $category_id with the ID of the category that you would like to display.
Best regards,
IsmaelOctober 15, 2024 at 10:55 am #1469139Thanks for the solution, but is it possible to select the category on each single product page? I wouldn’t want to put it globally, perhaps by inserting a css in the related products widget on each single product page?
October 16, 2024 at 8:51 am #1469191Hi,
Thank you for the update.
You can apply a custom field called av_related_category_id to the product and use the ID of the category you’d like to display as its value. We also updated the filter to accommodate these changes.
add_filter( 'woocommerce_related_products', 'avf_custom_related_products_by_custom_field', 10, 3 ); function avf_custom_related_products_by_custom_field( $related_posts, $product_id, $args ) { $category_id = get_post_meta( $product_id, 'av_related_category_id', true ); if ( ! $category_id ) { return $related_posts; } $related_products = get_posts( array( 'posts_per_page' => $args['posts_per_page'], 'post_type' => 'product', 'fields' => 'ids', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $category_id, ), ), ) ); return $related_products; }
Best regards,
Ismael -
AuthorPosts
- You must be logged in to reply to this topic.