Wordpress: Get Posts By Custom Field Values

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; ?>
  1. Christina:

    This is a great snippet of code! Would it be possible to list a key’s values??

    For example if my key was ‘cheese’ could I produce a ul of all the values, like:

    - wenslydale
    - cheddar
    - stilton
    - gogonzola

    Christina :)

  2. Miss75:

    Outcomes Assessment: Views and Perspectives. ,

  3. Crazy90:

    List 3 adjectives that describe how you feel when you wear these shoes. ,

Leave a Reply