Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Get or update post meta via the WordPress REST API
*
* @param int $post_id Post ID to get meta for.
* @param bool|string $json_url Optional. Base URL for API. If false will use current site's API URL.
* @param array $headers Headers to use in request. Must at least include authorization.
* @param bool $update Optional. If true updates meta value, if false just returns current values.
* @param bool|array $meta_data Optional, but required if updating. Array of key => value for meta ID being updated.
* @param bool|int $meta_id Optional. ID of meta key to update. If not specified and updating an additional HTTP request is required to find it.
*
* @return string|WP_Error|JSON
*/
function jp_mini_rest_client_remote_meta( $post_id, $json_url = false, $headers, $update = true, $meta_data = false, $meta_id = false ) {
//get base URL if not provided
if ( ! $json_url ) {
//return error if no url provided and REST API isn't installed on this site
if ( ! function_exists( 'json_url' ) ) {
return __( 'You must provide a remote JSON url, or install the REST API plugin on this site.', 'jp-mini-rest-client' );
}
$json_url = json_url();
}
//begin setting up arguments for wp_remote_get()
$args = array(
'headers' => $headers,
'method' => 'GET',
'body' => '',
);
//add meta endpoint to url
$json_url = trailingslashit( $json_url ). "posts/{$post_id}/meta/";
//If trying to update, add the meta ID to url if we have it, if not retrieve it.
if ( $update && $meta_id && intval( $meta_data ) > 0 ) {
$json_url .= $meta_id;
} else{
$response = wp_remote_get( $json_url, $args );
if ( ! is_wp_error( $response ) && ! is_null( $response ) ) {
$response = json_decode( $response[ 'body' ] );
foreach( $response as $meta ) {
if ( isset( $meta->key ) && $meta->key === $meta_data[ 'key' ] ) {
$meta_id = $meta->ID;
break;
}
}
}
if ( ! $meta_id ) {
$message = __( sprintf( 'Meta key %1s does not appear to exist.', $meta_data[ 'key' ] ), 'jp-mini-rest' );
return new WP_Error( 'no-key', $message );
}
}
//if updating change to post, add the data to body and change endpoint to include ID.
if ( $update && is_array( $meta_data ) ) {
$args[ 'method' ] = 'POST';
$args[ 'body' ] = json_encode( $meta_data );
$json_url .= $meta_id;
}
//make request
$response = wp_remote_post( $json_url, $args );
//return if not error
if ( ! is_wp_error( $response ) ) {
return $response[ 'body' ];
}
else{
if ( WP_DEBUG_DISPLAY ) {
return $response;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment