-
-
Save vagelisp/322e2a031fa9a12e1777f942dc46370c to your computer and use it in GitHub Desktop.
WordPress / Get Post by Meta Value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get Post object by post_meta query | |
* | |
* @use $post = get_post_by_meta( array( 'meta_key' => meta_name, 'meta_value' => value, 'post_type' => post_type, 'post_per_page' => post_per_page ) ) | |
* @since 1.0.5 | |
* @return Object WP post object | |
*/ | |
function get_post_by_meta( $args = array() ) { | |
$args = (object) wp_parse_args( $args ); | |
$args = array( | |
'meta_query' => array( | |
array( | |
'key' => $args->meta_key, | |
'value' => $args->meta_value, | |
), | |
), | |
'post_type' => $args->post_type, | |
'posts_per_page' => $args->post_per_page, | |
); | |
$posts = get_posts( $args ); | |
if ( ! $posts || is_wp_error( $posts ) ) { | |
return false; | |
} | |
return $posts[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment