• Resolved nemci7v

    (@nemci7v)


    I created a custom meta for my posts and I’m trying to echo the number of posts with a certain meta.

    In a query loop

    ...
    query_posts('meta_value=' . $some_value);
    ...

    I used

    $count_posts = wp_count_posts();
    echo $count_posts;

    but I get this error

    Catchable fatal error: Object of class stdClass could not be converted to string

    I’m not sure if the wp function can be used with meta.. should I just use a normal query?

    SELECT COUNT(*) FROM $wpdb->posts WHERE custom_meta = $some_value

Viewing 3 replies - 1 through 3 (of 3 total)
  • vtxyzzy

    (@vtxyzzy)

    Give this a try:

    // Replace these with your meta_key and meta_value
    $meta_key = 'x';
    $meta_value = '2';
    
    $sql = "SELECT count(DISTINCT pm.post_id)
    FROM $wpdb->postmeta pm
    JOIN $wpdb->posts p ON (p.ID = pm.post_id)
    WHERE pm.meta_key = '$meta_key'
    AND pm.meta_value = '$meta_value'
    AND p.post_type = 'post'
    AND p.post_status = 'publish'
    ";
    $count = $wpdb->get_var($sql);
    echo "<p>Count is: $count</p>";

    You could use this with query_posts, but it is less efficient to select entire posts just to get a count:

    ...
    query_posts('meta_key=my-key-name&meta_value=' . $some_value);
    echo $wp_query->found_posts;
    ...
    Thread Starter nemci7v

    (@nemci7v)

    vtxyzzy that’s brilliant your code worked perfectly without any issues! Thanks so much! ??

    vtxyzzy

    (@vtxyzzy)

    You are welcome!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Counting posts that contain a custom meta’ is closed to new replies.