I have this function hardcoded into content-single-product.php (WooCommerce) and it works to show 3 random products from categories ID 64 and 72:
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '3',
'orderby' => 'rand',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => array( 64, 72 ),
),
),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
Now, instead of hardcoding the category ID, I added a custom field to the product MyCustomField
and wrote 64,72 in it. Then I tried to modify the above code to be populated dynamically:
$MyCustomField = get_post_meta($post->ID, 'MyCustomField', true);
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '3',
'orderby' => 'rand',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => array( $MyCustomField ),
),
),
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
Unfortunately, this doesn’t work correctly:
'terms' => array( $MyCustomField )
because it only displays products from the first category (ID 64), and not from both, as I want.
I’m a newbie programmer so what did I do wrong? Thanks!