Wordpress: Get Posts By Custom Field Values

January 3rd, 2009

Thought Wordpress nerds might find this useful, a function to retrieve a list of posts by passing in a custom filed key=>value pair, with an optional count parameter.

Just drop this in your “functions.php”:

function getPostsByMeta($key, $value, $count = -1)
{
    global $wpdb;
 
    $sql = "SELECT DISTINCT wp_posts.post_title,
    wp_posts.ID FROM $wpdb->posts,
    $wpdb->postmeta 
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
    AND $wpdb->posts.post_status = 'publish' 
    AND $wpdb->postmeta.meta_key = '$key' 
    AND $wpdb->postmeta.meta_value = '$value' 
    ORDER BY post_date DESC";
 
    $sql .= ($count != -1) ? " LIMIT ".$count : "" ; 
 
    return $wpdb->get_results($sql);
}

and then you can use it like this:

$news_home = getPostsByMeta('_tb_post_section', 'News', 3); 
 
<?php foreach ($news_home as $news) : ?>
    <!-- OUTPUT TEMPLATED HTML -->
<?php endforeach; ?>