【问题标题】:MySQL Query on Wordpress databaseWordpress 数据库上的 MySQL 查询
【发布时间】:2013-03-20 21:13:41
【问题描述】:

我想在 wordpress 数据库上进行 mysql 查询,以恢复最近 6 个帖子的标题和第一个图片链接。

不允许使用 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>";
}

但是如何恢复附加到这些帖子的第一张图片(如果存在)?

【问题讨论】:

  • 图片在哪里?
  • 图片链接在wordpress数据库中(post_type=attachement, guid=url_to_the_image),文件位于wordpress网站的上传文件夹中

标签: php mysql sql database wordpress


【解决方案1】:

对于您在 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';

【讨论】:

  • 感谢您的回答,但它对我不起作用。我确认在我的 wordpress db post_parent 中指向已发布的页面
  • 在对我的情况进行了一些调整后,它现在可以工作了。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 2018-01-14
  • 1970-01-01
相关资源
最近更新 更多