首页 > 解决方案 > 在 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', '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 获取发布 MetaBox 值,因为,get_post_meta返回(我猜)一些关系?

标签: wordpressrestwordpress-rest-apimeta-boxes

解决方案


您必须使用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看到返回值。


推荐阅读