I have an old function which uses the post excerpt to hold the image thumbnail. It was a bit hackey and worked for a long time.
Now I need to use the post excerpt for, you know, an excerpt. So I’m looking to update this function to grab the image src info straight from the post attachments instead.
The question:
How can I update the $before_sql
SQL code below to grab the first attached image in the post attachment?
The code:
(I think I am only concerned about the sql portion as the rest should clean itself up?) There’s more code section too, but instead of pasting ALL of it here, this snippet should be enough.
$before_sql = "SELECT ID, post_title, post_excerpt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' and post_date < '$cur_post_date' ORDER BY post_date DESC LIMIT $thumbnum";
$before_results = $wpdb->get_results($before_sql);
if($before_results) {
foreach ($before_results as $before_result) {
$post_title = stripslashes($before_result->post_title);
$permalink = get_permalink($before_result->ID);
$post_excerpt = ($before_result->post_excerpt);
$output="<div class="thumbnails"><a href="" . $permalink . "" title="Permanent Link: " . $post_title . "">" . $post_excerpt . "</a><br />‹</div>n " . $output;
}
}
To get the first attachment with the posts in one query you can do in this way
ORDER BY post_date ASC will get the first image if you want the latest uploaded image you can simply use DESC ORDER BY post_date DESC
Here is your query
It works fine for me
This is the query which will fetch those posts only which has the attachments on it