Skip to content

Instantly share code, notes, and snippets.

@luisabarca
Last active February 24, 2016 00:25
Show Gist options
  • Save luisabarca/fc2669cfc9d4c906c235 to your computer and use it in GitHub Desktop.
Save luisabarca/fc2669cfc9d4c906c235 to your computer and use it in GitHub Desktop.
Get a WordPress post with a specific value in the custom fields
<?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