TEL:400-8793-956
当前位置:程序、服务器

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

提问者: 近期获赞: 浏览人数: 发布时间:2022-02-14 09:38:15

 问:我为我的博客文章的网站创建了一个自定义 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);
?>
那么,有没有办法可以在我的 JSON API 中添加特色图片 URL?任何答案将不胜感激!
 
 
答:0
 
要获取您需要的特色图片_thumbnail_id,您可以从该 id 获取图片 URL。_thumbnail_id您可以在帖子元表中找到。试试下面的查询。
 
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'],
上一篇: 尝试从对象创建和排列时出错
下一篇: PHP双while循环[关闭]