0

I have got main product with meta key: addons and meta values in this key: 129456,968945,495435 Each of these three numbers is the key with these meta values. For example:

Post 1: meta_key: subproduct meta_value: 129456

Post 2: meta_key: subproduct meta_value: 968945

Post 3: meta_key: subproduct meta_value: 495435

And now I want to display these three posts in the main product. My code:

<?php if (!empty($addons = get_post_meta(get_the_ID(), 'addons', true))):?>
<?php
$params = array(
    'post_type' => 'product',
    'meta_key' => 'subproduct',
    'meta_value' => $addons
);
$wc_query = new WP_Query($params); 
?>

<?php while ($wc_query->have_posts()) : $wc_query->the_post(); ?>
<?php include(rh_locate_template('inc/parts/woomain.php')); ?>  
<?php endwhile; ?>


<?php wp_reset_postdata(); ?>   
<?php endif;?>

With one meta value it worked but with several it doesn't work anymore. How do you view these three posts?

1 Answer 1

0

The meta field Addon have the meta value 129456,968945,495435 as string. To use this value in a meta query, you should split the value into an array. Like array( 129456, 968945, 495435 ).

WordPress have a very good function wp_parse_id_list(), which can split comma separated items into array.

<?php if ( ! empty( $addons = get_post_meta( get_the_ID(), 'addons', true ) ) ) : ?>
<?php
$params = array(
    'post_type' => 'product',
    'meta_key' => 'subproduct',
    'meta_value' => wp_parse_id_list( $addons )
);
$wc_query = new WP_Query($params); 
?>

<?php while ($wc_query->have_posts()) : $wc_query->the_post(); ?>
<?php include(rh_locate_template('inc/parts/woomain.php')); ?>  
<?php endwhile; ?>


<?php wp_reset_postdata(); ?>   
<?php endif;?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.