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:

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?


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
  • Thank you s_ha_dum! I wonder why I can't query by post_title: I didn't notice that wasn't an option. Also I appreciate your improvement advice to make the query lighter: I already save the result in a transient that expires each few minutes, but it's always good to improve the code :) However, in some cases is not possible to edit the image slug (and I need to allow editors to set the "no-title" for any image I upload). For anyone interested, here is a way to make WP_Query filter by post_title: wordpress.stackexchange.com/questions/22949/query-post-by-title – Andrea Sciamanna Apr 30 '13 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.