最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Display posts from multiple value in meta separated by comma

programmeradmin4浏览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?

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?

Share Improve this question asked Apr 12, 2020 at 15:05 Lucas SmithLucas Smith 112 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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;?>
发布评论

评论列表(0)

  1. 暂无评论