Get posts by meta key and meta value wordpress

Get posts by meta key and meta value wordpress

In this blog i will show you how to get posts in wordpress using meta_key and meta_value. For this I will pass meta_query as arguments in WP_Query function to get posts with post type.

Also Read: Get custom post types in wordpress

I have created a custom post type `books` using post type generator. you can create custom post type with post type generator and add that code in your functions.php. Use below code to get posts using meta_key and meta_value. 

$args = array(
'post_type'      => 'books',
'posts_per_page' => 4,
'meta_query'     => array(
    array(
'key'   => 'book_type',
'value' => 'pdf',
    ),
)
);

$query = new WP_Query( $args );
if ( $query->posts ) {
foreach ( $query->posts as $key => $post_id ) {
get_the_title();
}
}

 

Hi, I'm Saurav, the developer behind usingphp. Donate to help me keep usingphp free and maintained.

Please let me know what your thoughts or comments are on this article. If you have any suggestion or found any mistake in this article then please let us know.

Latest Comments

Add your comment