Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get all post by post meta key and meta value using meta_query in WP_Query(). Read more at https://wp.me/p4Ams0-14E
<?php
/**
* Get all post by post meta key and meta value.
*
* @todo Change the `prefix_` and with your own unique prefix.
*
* @since 1.0.0
*/
if( ! function_exists( 'prefix_search_post_by_post_meta_value' ) ) :
function prefix_search_post_by_post_meta_value() {
$query_args = array(
'post_type' => 'post',
// Query performance optimization.
'fields' => 'ids',
'no_found_rows' => true,
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'my-meta-key',
'value' => 'my-meta-value',
),
)
);
$query = new WP_Query( $query_args );
if ( $query->posts ) {
foreach ( $query->posts as $key => $post_id ) {
// var_dump( $post_id );
// Code goes here..
}
}
}
add_action( 'admin_head', 'prefix_search_post_by_post_meta_value' );
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment