Search code examples
wordpressrestwordpress-rest-apimeta-boxes

Get MetaBox value inside WP Rest API


I have a registered meta box:

    $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,
        ],
    ],
];

I am trying to get that MetaBox value like so:

$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
];

, but the $meta is an integer like 2225. The post has this metabox populated.

If I try with the standard Rest API endpoint, I am getting the value:

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

My question is how to get a post MetaBox value via Rest API with a custom endpoint, because, get_post_meta, returns (I guess) some relation ?


Solution

  • You must use 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 );
    }
    

    And you can see wp_get_attachment_image_src returning value here.