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!

3 s
3

I suspect the problem is coming from $MyCustomField which you enter as such in:

'terms' => array( $MyCustomField ),

The query consider it as only one value: '64,72', a string.

So try:

$MyCustomFieldValues = array_map( 'intval', explode( ',', $MyCustomField ) );

This will also ensure your values are integers.

Then:

'terms' => $MyCustomFieldValues,

Leave a Reply

Your email address will not be published. Required fields are marked *