custom post types - How do I get a meta value from WP_Query?

admin2025-01-07  3

I've got the custom post type foo with meta fields called bar and baz. Now I get the WP_Query object using:

$args = array( 
       'post_type'      => 'foo', 
       'meta_key'       => 'bar', 
       'meta_value'     => $bar_value,
       'posts_per_page' => 10,
);
$res = new WP_Query($args);

Now I want to check if the value baz of the selected post is equal to $baz_value. How can I do that?

I've got the custom post type foo with meta fields called bar and baz. Now I get the WP_Query object using:

$args = array( 
       'post_type'      => 'foo', 
       'meta_key'       => 'bar', 
       'meta_value'     => $bar_value,
       'posts_per_page' => 10,
);
$res = new WP_Query($args);

Now I want to check if the value baz of the selected post is equal to $baz_value. How can I do that?

Share Improve this question edited Oct 10, 2013 at 15:19 Joren asked Oct 10, 2013 at 14:13 JorenJoren 3171 gold badge5 silver badges23 bronze badges 1
  • 1 See meta_query for WP_Query – Milo Commented Oct 10, 2013 at 14:18
Add a comment  | 

4 Answers 4

Reset to default 3

I've found a solution to my problem myself. Since none of the already existing answers solved the problem, I figured I could best post mine here to help people with similar problems.

The solution:

if($res->have_posts()) { 
    $id = $mail_res->posts[0]->ID; // blindly assuming there is only 1 post having baz = baz_value
    $true_baz = get_post_meta($id, 'baz')[0];

    if($true_baz== $baz) {
        //success
    } else {
        //error
    }
} else {
    //error
}

Did you tried this one:

$args = array( 
   'post_type'      => 'foo', 
   'meta_key'       => 'bar', 
   'meta_value'     => $bar_value,
   'posts_per_page' => 10,
);
$res = new WP_Query($args);

 to 
  $args = array( 
   'post_type'      => 'foo', 
   'meta_key'       => 'bar', 
   'meta_value'     => $bar_value,
   'meta_compare'     => '=',
   'posts_per_page' => 10,
);
$res = new WP_Query($args);

Read this: WP_Query

The query arguments are in several places in the query object. You can var_dump the object and see them.

  1. $res->query_vars
  2. $res->meta_query (in this case)
  3. $res->query

Items 1 and 3 will be easiest to work with. Simple PHP object and array syntax will get the information you need.

<?php
  $args = array(
    'post_type' => 'myvideos',
    'posts_per_page' => '1'
  );

  $query = new WP_Query($args);
?>

<?php if($query->have_posts()):while($query->have_posts()): $query->the_post(); ?>

 
/*
where url is your custom filed name and we are retrieving value at index one as metadata can have array of url values.
*/

  <?php $data = get_post_meta(get_the_id(), 'url')[0];?>

<?php endwhile; else: endif;?>
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736259653a605.html

最新回复(0)