在 WP Rest API 中获取 MetaBox 值

问题描述

我有一个注册的元框:

    $Meta_Boxes[] = [
    'title'   => esc_html__( 'Background','background' ),'id'      => 'background','context' => 'normal','post_types' => array('post','page'),'fields'  => [
        [
            'type'             => 'image_advanced','name'             => esc_html__( 'Background','id'               => 'background','max_file_uploads' => 1,],];

我正在尝试像这样获得 MetaBox 值:

$query = new WP_Query( $args );


$page = $query->post; // there is a post

$Meta = get_post_meta($page->ID,'background',true); // $page->ID is integer

return [
    'uri' => $uri,'ID' => $page->ID,'page' => $query->post,'Meta' => $Meta
];

,但 $Meta一个整数,如 2225。 该帖子已填充此元数据框。

如果我尝试使用标准的 Rest API 端点,我会得到值:

.... post data
 "Meta_Box": {
    "background": [
        {
            "width": 150,"height": 150,"file": "2020/10/163593234-e1603902300928.jpg",........

我的问题是如何通过带有自定义端点的 Rest API 获取 post MetaBox 值,因为 get_post_meta 返回(我猜)一些关系?

解决方法

您必须使用 wp_get_attachment_image_src

$meta = get_post_meta( $page->ID,'background',true ); // $page->ID is integer

if( $meta ) {
    $img = wp_get_attachment_image_src( $meta );
}

您可以看到 wp_get_attachment_image_src 返回值 here