Forked from tzkmx/get_thumbnail_to_category_rest.php
Created
September 27, 2021 09:37
-
-
Save fencermonir/f720097a243f1c55e26f12e4fd214ce8 to your computer and use it in GitHub Desktop.
Add thumbnail field to WordPress category via REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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