If you are into developing custom themes for WordPress, you probably know how useful it can be to use custom meta fields in your posts. But only adding those fields is not enough. You need custom loops or functions to filter/get your posts using those meta values. In this post, we share with you a basic PHP code snippet for getting post id by meta value.


How to Get Post Id by Meta Value in WordPress

Using WP_Query

If you need to use post id in a loop, the recommended way of using custom loops is the WP_Query method. This method doesn’t modify the default query so it is safer. Here is the sample code for getting post objects using meta values:

<?php 

/* Post Arguments */
$args = array(
  'post_type' => 'post',
  'ignore_sticky_posts' => 1,
  'meta_key' => 'color',
  'meta_value' => 'red',
  'meta_compare' => '!='
);

/* Using WP_Query */
$my_query = new WP_Query( $args );
if ( $my_query->have_posts() ) :
  while ( $my_query->have_posts() ) : $my_query->the_post();

    $post_id = get_the_ID(); /* We get ID here */

    ... Do You Stuff .. 

?>

    <h3><?php the_title(); ?></h3>

<?php
  endwhile;
endif; 

wp_reset_postdata(); /* Reset post data to original query */

?>
</ins>

The magic in this code happens when you call $my_query->the_post() function. This function prepares all post-template functions using the current post object. So when you call get_the_ID function you get the ID of the current post in the loop.

Using get_posts

You can also get posts using get_posts function. The only difference between get_posts and WP_Query is that using get_posts you get an array of post objects. It is generally used for special cases like generating post navigations etc. Here is a sample using get_posts function:

</ins>
<?php 

$args = array( 
  'post_type' => 'post', 
  'ignore_sticky_posts' => 1, 
  'meta_key' => 'color', 
  'meta_value' => 'red', 
  'meta_compare' => '!=' 
);

$postlist = get_posts( $args );

foreach ( $postlist as $post ) {
  setup_postdata( $post ); ?>

    <h3><?php the_title(); ?></h3>

    <!-- You can use any post specific template function here -->

<?php 
}

?>

Since the returned object is an array of posts in this function, we need to call setup_postdata function after using get_posts.


Conclusion

In this post, I have tried to show you basic examples of how to get post id using meta_value of custom fields. If you liked this tip, don’t forget to share it with your friends. Enjoy!