Reputation: 157
I am trying to display products by meta value and meta key. I am using the code below to validate the meta_key and meta_value. Now if there are no meta_keys with the value "yes_feat" no products print. Which is great!
The problem is, if there is only 1 product that has the meta_keys with the value "yes_feat" all the other products print as well. How do I make it so only the products with the meta_value "yes_feat" display
$params = array(
'post_type' => 'product',
'meta_key' => '_featured',
'meta_value' => 'yes_feat',
'posts_per_page' => 5
);
$wc_query = new WP_Query($params);
global $post, $product;
if ($wc_query->have_posts()) {
// i am only trying to print products with meta_value = yes_feat
// but if the statement above is true it prints all products
echo "print products that have meta_value = yes_feat";
}
else
{
echo "nothing found";
}
Thanks alot
Upvotes: 1
Views: 11056
Reputation: 2887
add meta query in WP_Query argument
<?php
$params = array(
'post_type' => 'product',
'meta_query' => array(
array('key' => '_featured', //meta key name here
'value' => 'yes_feat',
'compare' => '=',
)
),
'posts_per_page' => 5
);
$wc_query = new WP_Query($params);
global $post, $product;
if( $wc_query->have_posts() ) {
while( $wc_query->have_posts() ) {
$wc_query->the_post();
$wc_query->post_name;
echo "print products that have meta_value = yes_feat";
$yes_feat = get_post_meta($wc_query->ID, '_featured',true );
} // end while
} // end if
else
{
echo "nothing found";
}
wp_reset_postdata();
?>
Upvotes: 6