php - MySQL 查询 WordPress 数据库

标签 php mysql sql database wordpress

我希望对 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>";
}

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

最佳答案

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

关于php - MySQL 查询 WordPress 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15534833/

相关文章:

javascript - 如何使用json读取html中的php数据

php - 使用 mysqldump 将表数据导出到 csv 文件

sql - 发生冲突时,如果 PostgreSQL 中的 json 值不同则更新?

PHP 表单验证并提交到另一个页面

mysql - SQLSTATE[42S22] : Column not found: 1054 Unknown column 'id' in 'where clause' (SQL update. .) 其中 `id` 为空)

c# - 获取异常 "There is already an open DataReader associated with this Connection which must be closed first."

php - 仅获取连接表中选定的列

mysql - 查询表中的所有数据,仅连接连接表中的最新记录

sql - 使用 IN 和 OUT 参数调用 Oracle 中的存储过程

php - 无法将日期字段从 csv 导入到 mysql