WP_Query returns more results than expected

I’ve written a query that is supposed to return all attachments called “no-image” (is part of a function that handle images fallback when there isn’t a featured image), the if I get some result, the function returns the first item.

Here’s the code:

Read More
function misamee_get_image_placeholder($size, $icon = false, $attr = '')
{
    $transient_key = 'image_placeholder_id';
    $result = get_transient($transient_key);

    if (!$result || empty($result)) {
        $image_name = "no-image";

        $query_args = array(
            'post_type' => 'attachment',
            'post_status' => 'inherit',
            'post_title' => $image_name
        );

        $query = new WP_Query($query_args);
        //echo '<pre>' . print_r($query, true) . '</pre>';

        if ($query->have_posts()) {
            $post = $query->posts[0];
            $result = $post->ID;
        }

        if ($result) {
            set_transient($transient_key, $result, CONTENT_CACHE_LIFETIME);
            return wp_get_attachment_image($result, $size, $icon, $attr);
        }
    }
    return false;
}

The problem is that this query is clearly ignoring the “post_title” argument, returning all attachments, and therefore returning the last uploaded image (see the commented echo '<pre>' . print_r($query, true) . '</pre>';).

What it’s wrong in my query?

Related posts

Leave a Reply

1 comment

  1. There is no post_title in WP_Query‘s parameter list. You need to use name, which accepts a slug not the actual post title.

    name (string) – use post slug.

    It looks like all you are doing is getting an ID. That is a very heavy query if that is all you need. You can alter the parameters to lighten this up.

    $query_args = array(
        'post_type' => 'attachment',
        'post_status' => 'inherit',
        'posts_per_page' => 1, // since you seem to be using only the first result
        'ignore_sticky_posts' => true, // don't juggle sticky posts to the top
        'no_found_rows' => true, // don't calculate total returns
        'name' => $image_name,
        'fields' => 'ids' // only return the post IDs
    );