REST API Requests and Shared Media Library
In this guide I am going to show you how to correctly send specific REST API requests to sub-sites of your multisite network when you have my shared media library plugin installed.
REST API requests (both WordPress and WooCommerce) are now supported by the plugin (since the 1.2 version).
The whole idea comes down to the following:
| Library type | How image IDs are processed |
|---|---|
| “Display shared media in a separate tab” | You either need to use local image IDs or to provide a parameter global (or featured_media_global) set to true |
| “Replace local media library” | You need to provide global image IDs in your REST API requests. |
Now, let’s jump into the examples.
Set a featured image to a post
For example, let’s say that you would like to create a post with a featured image, and at the same time you are using a library type “Display shared media in a separate tab” in the plugin settings.
Then, by default, a featured image ID in REST API requests is going to be taken from the local media library. If you want to use images from the network media library, you need to provide one more parameter featured_media_global, or, if it is not possible, to switch to another library type.
Here is a request example:
$response = wp_remote_post(
"{$url}/wp-json/wp/v2/posts",
array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( "{$username}:{$pwd}" )
),
'body' => array(
'title' => 'My test',
'status' => 'draft',
'featured_media' => 157,
'featured_media_global' => true,
)
)
);Get a global featured image of a post
For the following REST API endpoints:
/wp/v2/posts/(any custom post type),- and
/wp/v2/posts/{$post_id}
the shared media library plugin adds one more response parameter featured_media_global, which contains all the media information of the network featured image.
You can check the example here.
Creating or updating media files via REST API
This part is not touched by my plugin. If you want to update a media on the primary site, just use its URL as a part of a REST API endpoint, if you want to update it on a sub-site – use a sub-site URL.
As simple as that.
WooCommerce
Create a product with an image
The idea is the same if you’re using the “Replace local media library” as a library type, then just feel free to pass media IDs from the network library to your REST API requests.
In case you’re using another library type, please provide the global parameter set to true.
Example:
$response = $woocommerce->post(
'products',
array(
'name' => 'Misha Test Product',
'type' => 'simple',
'regular_price' => '23.00',
'images' => array(
// let's set the main product image here
array(
'id' => 12345,
'global' => true,
),
),
)
);Create a product category with an image
The same way it works for product variations, by the way.
$response = $woocommerce->post(
'products/categories',
array(
'name' => 'Misha Test Category',
'image' => array(
'id' => 12345,
'global' => true,
),
)
);