2
votes

I've been trying to customize related products in woocommerce. I've used woocommerce_output_related_products_args to add meta_query options, but they have no effect, this is my code:

add_filter( 'woocommerce_output_related_products_args', 
'custom_related_products_args' );
 function custom_related_products_args( $args ) {
$args['posts_per_page'] = 4;
$args['columns'] = 4;
$args['meta_query'] = array(
    array(
        'key' => 'public_catalog',
        'value' => true
    ),
); 
return $args;}
1

1 Answers

4
votes

The correct filter hook to alter related products query is woocommerce_product_related_posts_query… To set a post meta query you will use the following (see the note at the end):

add_filter( 'woocommerce_product_related_posts_query', 'alter_product_related_posts_query', 10, 3 );
function alter_product_related_posts_query( $query, $product_id, $args ){
    global $wpdb;

    $query['join']  .= " INNER JOIN {$wpdb->postmeta} as pm ON p.ID = pm.post_id ";
    $query['where'] .= " AND pm.meta_key = 'public_catalog' AND meta_value LIKE '1' ";

    return $query;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Note: In backend (Admin) under Woocommerce > Status > Tools > "WooCommerce transients" click on "Clear transients" button