如何在 WordPress 中通过 SQL 查询获取特色图片?

How get featured image via SQL query in WordPress?

我已经为我的博客帖子创建了自定义 JSON API,但我找不到任何方法将特色图片 URL 添加到 API.这是我的 API:

<?php
header("Content-Type: application/json");
require_once 'wp-connect.php';

$result = [];
$sql = <<<SQL
SELECT * 
FROM wp_users
INNER JOIN wp_posts ON wp_users.ID = wp_posts.post_author AND wp_posts.post_type = 'post'
INNER JOIN (
    SELECT user_id,
           MAX(IF(meta_key = 'first_name', meta_value, NULL)) AS first_name,
           MAX(IF(meta_key = 'last_name', meta_value, NULL)) AS last_name,
           MAX(IF(meta_key = 'avatar_hash', meta_value, NULL))AS avatar_hash
    FROM wp_usermeta
    GROUP BY user_id
) pivoted ON pivoted.user_id = wp_users.ID
ORDER BY wp_posts.ID
SQL;
foreach (mysqli_query($conn, $sql) as $row) {
    $result[] = [
        'post_id' => $row['ID'],
        'user_id' => $row['post_author'],
        'post' => $row['post_content'],
        'firstName' => $row['first_name'],
        'lastName' => $row['last_name'],
        'username' => $row['user_nicename'],
        'avatar' => $row['avatar_hash'],
        'post_date' => $row['post_date'],
        'post_type' => $row['post_type'],
        'post_title' => $row['post_title'],
        'post_name' => $row['post_name'],
        'post_modified' => $row['post_modified'],
    ];
}
echo json_encode($result, JSON_PRETTY_PRINT);
?>

那么,有什么方法可以将特色图片 URL 添加到我的 JSON API 中?任何答案将不胜感激!

要获取您需要的特色图片 _thumbnail_id,您可以从该 ID 获取图片 URL。 _thumbnail_id 您可以在 post 元 table 中找到。试试下面的查询。

header("Content-Type: application/json");
require_once 'wp-connect.php';

$result = [];
$sql = <<<SQL
SELECT *,
    (
        SELECT guid
        FROM   wp_posts
        WHERE  id = wp_postmeta.meta_value
    ) AS image 
FROM wp_users
INNER JOIN wp_posts ON wp_users.ID = wp_posts.post_author AND wp_posts.post_type = 'post'
INNER JOIN wp_postmeta ON wp_postmeta.post_id = wp_posts.id AND wp_postmeta.meta_key = '_thumbnail_id'
INNER JOIN (
    SELECT user_id,
           MAX(IF(meta_key = 'first_name', meta_value, NULL)) AS first_name,
           MAX(IF(meta_key = 'last_name', meta_value, NULL)) AS last_name,
           MAX(IF(meta_key = 'avatar_hash', meta_value, NULL))AS avatar_hash
    FROM wp_usermeta
    GROUP BY user_id
) pivoted ON pivoted.user_id = wp_users.ID
ORDER BY wp_posts.ID;
SQL;

foreach ( mysqli_query($conn, $sql) as $row ) {
    $result[] = [
        'post_id'       => $row['ID'],
        'user_id'       => $row['post_author'],
        'post'          => $row['post_content'],
        'firstName'     => $row['first_name'],
        'lastName'      => $row['last_name'],
        'username'      => $row['user_nicename'],
        'avatar'        => $row['avatar_hash'],
        'post_date'     => $row['post_date'],
        'post_type'     => $row['post_type'],
        'post_title'    => $row['post_title'],
        'post_name'     => $row['post_name'],
        'post_modified' => $row['post_modified'],
        'image'         => $row['image']
    ];
}