2

我有一个旧功能,它使用帖子摘录来保存图像缩略图。这有点hackey并且工作了很长时间。

现在我需要使用帖子摘录,你知道,摘录。因此,我希望更新此功能以直接从帖子附件中获取图像 src 信息。

问题:

如何更新$before_sql下面的 SQL 代码以获取帖子附件中的第一个附加图像?

编码:

(我想我只关心 sql 部分,因为其余部分应该自行清理?)还有更多的代码部分,但是不要在这里粘贴所有这些,这个片段应该足够了。

$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 />&lsaquo;</div>\n         " . $output;
    }
}
4

1 回答 1

3

要在一个查询中获取包含帖子的第一个附件,您可以这样做

SELECT *,
(SELECT guid FROM `wp_posts`  WHERE post_type ='attachment' AND post_parent=wp.`ID` ORDER BY post_date ASC LIMIT 1 ) AS attachment
 FROM `wp_posts` wp 

ORDER BY post_date ASC将获取第一张图片如果您想要最新上传的图片,您可以简单地使用 DESC ORDER BY post_date DESC

这是您的查询

$before_sql = "SELECT ID, post_title, post_excerpt,
(SELECT guid FROM $wpdb->posts  WHERE post_type ='attachment' AND post_parent=wp.`ID`
ORDER BY post_date ASC LIMIT 1 ) AS attachment
FROM $wpdb->posts wp WHERE wp.post_status = 'publish' AND wp.post_type = 'post'
and wp.post_date < '$cur_post_date' ORDER BY wp.post_date DESC LIMIT $thumbnum";

这对我来说可以

这是一个查询,它将只获取那些上面有附件的帖子

$before_sql = "SELECT ID, post_title, post_excerpt,
(SELECT guid FROM $wpdb->posts  WHERE post_type ='attachment' AND post_parent=wp.`ID`
ORDER BY post_date ASC LIMIT 1 ) AS attachment
FROM $wpdb->posts wp WHERE wp.post_status = 'publish' AND wp.post_type = 'post'
and wp.post_date < '$cur_post_date' HAVING attachment IS NOT NULL ORDER BY wp.post_date DESC LIMIT $thumbnum";
于 2013-08-09T16:00:36.557 回答