Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fencermonir/f720097a243f1c55e26f12e4fd214ce8 to your computer and use it in GitHub Desktop.
Save fencermonir/f720097a243f1c55e26f12e4fd214ce8 to your computer and use it in GitHub Desktop.
Add thumbnail field to WordPress category via REST API
<?php
add_action('rest_api_init', 'register_my_rest_field');
/**
* It depends on term_meta key _thumbnail_id using the metadata API
* for terms. Only plugin I know uses this is Taxonomy Thumbnail:
* https://wordpress.org/plugins/sf-taxonomy-thumbnail/ instead of
* storing metadata for terms in wp_options or custom tables
*/
function register_my_rest_field()
{
register_rest_field('category', 'thumbnail', [
'get_callback' => 'dummy_plug',
'update_callback' => null,
'schema' => [
'description' => 'Holds the thumbnail pic URL',
'type' => 'string',
'format' => 'url',
'context' => ['view'],
'readonly' => true,
]
]);
}
function dummy_plug($object, $field_name, $request) {
$attachment_id = get_term_meta($object['id'], '_thumbnail_id', true);
if(!$attachment_id) {
return;
}
$url = wp_get_attachment_url($attachment_id);
return $url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment