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
inWP_Query
‘s parameter list. You need to usename
, which accepts a slug not the actual post title.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.