如何在WP REST API中获取特色图像

时间:2021-04-04 作者:omid chahardoli

我使用以下代码从wp json rest api获取最新产品

// Get posts via REST API.
function get_posts_via_rest() {
    $allposts = \'\';
    $response = wp_remote_get( \'https://mysite .com/product/wp-json/wp/v2/product?per_page=4\' );
    if ( is_wp_error( $response ) ) {
        return;
    }
    $posts = json_decode( wp_remote_retrieve_body( $response ) );
    if ( empty( $posts ) ) {
        return;
    }
    if ( ! empty( $posts ) ) {
        foreach ( $posts as $post ) {
            $allposts .= \'<div class="jl_list_post_wrapper">
  <a href="\' . esc_url( $post->link ) . \'" class="jl_small_format feature-image-link image_post featured-thumbnail">
  <img src="\'. esc_html( $post->featured_image_src) .\'" class="attachment-disto_small_feature size-disto_small_feature wp-post-image"> <div class="background_over_image"></div>
  </a>
  <div class="item-details">
  <h3 class="feature-post-title"><a href="\' . esc_url( $post->link ) . \'">\' . esc_html( $post->title->rendered ) . \'</a></h3>
  <span class="post-meta meta-main-img auto_image_with_date">  <span class="post-date"><i class="fa fa-shopping-cart"></i> in stock</span></span> </div>
</div>\';
        }
        return $allposts;
    }
}
也可以使用下面的代码在api中生成特色图像

function post_featured_image_json( $data, $post, $context ) {
  $featured_image_id = $data->data[\'featured_media\']; // get featured image id
  $featured_image_url = wp_get_attachment_image_src( $featured_image_id, \'original\' ); // get url of the original size

  if( $featured_image_url ) {
    $data->data[\'featured_image_url\'] = $featured_image_url[0];
  }

  return $data;
}
add_filter( \'rest_prepare_post\', \'post_featured_image_json\', 10, 3 );
但这在我的网站上不起作用。你有没有办法得到缩略的产品图片?

以及如何在api中生成(库存)/(缺货)以显示给其他站点?

1 个回复
最合适的回答,由SO网友:user3542212 整理而成

通过将此代码添加到主题函数中,可以将特色图像添加到REST API中。php

// Add featured image to REST API
add_action(\'rest_api_init\', \'register_rest_images\' );
function register_rest_images(){
    register_rest_field( array(\'post\'),
        \'fimg_url\',
        array(
            \'get_callback\'    => \'get_rest_featured_image\',
            \'update_callback\' => null,
            \'schema\'          => null,
        )
    );
}
function get_rest_featured_image( $object, $field_name, $request ) {
    if( $object[\'featured_media\'] ){
        $img = wp_get_attachment_image_src( $object[\'featured_media\'], \'app-thumb\' );
        return $img[0];
    }
    return false;
}
然后,您应该在fimg\\u url下看到特色图像的url。