关于Wordpress数据库的MySQL查询

关于Wordpress数据库的MySQL查询

问题描述:

我想在wordpress数据库上有一个mysql查询,用于恢复标题和最近6篇文章的第一个图像链接。关于Wordpress数据库的MySQL查询

WordPress的核心功能是不允许的,因为我想在外部网站上显示它们。换句话说,我需要纯粹的mysql查询。

我能够表现出这样的标题:

$result = mysql_query("select * FROM wp_posts WHERE post_status='publish' AND post_type='ad_listing' ORDER BY id desc limit 6" ,$db); 
while ($records = mysql_fetch_assoc($result)) { 
    echo '<li>'.$records['post_title'] ."</li>"; 
} 

但如何恢复第一个图像(如果存在)连接到这些帖子?

+0

图像在哪里? – Kermit 2013-03-20 21:16:25

+0

图片链接在wordpress数据库中(post_type = attachement,guid = url_to_the_image),这些文件位于wordpress站点的上传文件夹中 – Avionicom 2013-03-20 21:19:39

对于wp_posts表中的图像记录,是否将post_parent点返回到已发布页面?我的没有,如果你的也没有,那么你需要搜索每个发布页面的post_content字段,寻找img标签(或者你用于图片的任何标签)。

从我读过的其他文章看来,有时图像的post_parent指向父页面。如果您的数据库的确如此,那么您应该可以这样做:

SELECT 
    post.id AS post_id, 
    post.post_title, 
    post.guid AS post_url, 
    image_detail.id AS image_id, 
    image_detail.post_title AS image_title, 
    image_detail.guid AS image_url 
FROM wp_posts AS post 
LEFT JOIN (
    SELECT post_parent, MIN(id) AS first_image_id 
    FROM wp_posts 
    WHERE post_type = 'attachment' 
     AND post_mime_type LIKE 'image/%' 
    GROUP BY post_parent 
    ) AS image_latest 
    ON post.id = image_latest.post_parent 
LEFT JOIN wp_posts AS image_detail 
    ON image_detail.id = image_latest.first_image_id 
WHERE post.post_status = 'publish'; 
+0

谢谢你的回答,但它对我不起作用。我确认在我的wordpress db post_parent指向已发布页面 – Avionicom 2013-03-21 20:47:36

+0

经过对我的案例的一些改编后,它现在可以工作。非常感谢你。 – Avionicom 2013-03-22 16:16:07