I am looking to filter the default output of the displayed related products on product pages. I need it to only return products with the same pa_merk attribute and products that are discounted.

I currently have the following (only based on the attribute for now), but can't get it to work as intended:

add_filter( 'woocommerce_related_products', 'filtered_related_products', 9999, 3 ); 
function filtered_related_products( $related_posts, $product_id, $args ) {
   $product = wc_get_product( $product_id );
   $brand = $product->get_attributes( 'pa_merk' );
   $related_posts = get_posts( array(
      'post_type' => 'product',
      'post_status' => 'publish',
      'taxonomy' => $brand,
      'fields' => 'ids',
      'posts_per_page' => -1,
      'exclude' => array( $product_id ),
   return $related_posts;

Any suggestions on how to improve this and also filter the products that are not being discounted? Also looked for similar questions/answers, but wasn't able to find a suitable solution to this.

Any help is greatly appreciated!

New contributor
Jonathan is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

Jonathan is a new contributor. Be nice, and check out our Code of Conduct.

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

Browse other questions tagged or ask your own question.