Last active
February 24, 2016 00:25
-
-
Save luisabarca/fc2669cfc9d4c906c235 to your computer and use it in GitHub Desktop.
Get a WordPress post with a specific value in the custom fields
This file contains hidden or 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
<?php | |
function get_post_by_custom_field($args) | |
{ | |
$defaults = array( | |
'post_type' => 'post', | |
'key' => '', | |
'value' => '', | |
'compare' => '=' | |
); | |
$args = wp_parse_args($args, $defaults); | |
$search = new WP_Query(array( | |
'post_type' => $args['post_type'], | |
'meta_query' => array( | |
array( | |
'key' => $args['key'], | |
'value' => $args['value'], | |
'compare' => $args['compare'] | |
) | |
) | |
)); | |
// found the post ? | |
if ($search->have_posts()) { | |
$search->the_post(); | |
// return the post | |
return $post; | |
} | |
return false; | |
} | |
// Example | |
$args = array( | |
'key' => 'uniqueid', | |
'value' => $uid, | |
'compare' => '=' | |
); | |
$post = get_post_by_custom_field($args); | |
// No post found ? | |
if (!$post) { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment