I use below code for get last products from 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;
}
}
And also use below code for generating featured images in 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 );
But this is not working in my website.
Do you have any idea to get thumbnail product image?
And how to generate (in stock) / (out of stock) in api to show to other site?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can add featured image to REST API by adding this code to your theme’s functions.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;
}
You should then see the url of the featured image under fimg_url.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0