Site icon Hip-Hop Website Design and Development

Filtering related products by attribute and discounted products

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!