Created
December 18, 2021 07:01
-
-
Save jb510/68c092853a8bcae1c6c5b886a49da97e to your computer and use it in GitHub Desktop.
Register custom taxonomy on woocommerce product and add to REST API
This file contains hidden or 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
/* | |
Simple Taxonomy */ | |
add_action( 'init', function() { | |
register_extended_taxonomy( 'customtax', 'product' ); // This relies on https://github.com/johnbillion/extended-cpts/ | |
} ); | |
//Register taxonomy API for WC | |
add_action( 'rest_api_init', function() { | |
register_rest_field('product', 'customtax', array( | |
'get_callback' => 's9_product_get_callback', | |
'update_callback' => null, // 's9_product_update_callback', | |
'schema' => null, | |
)); | |
} ); | |
//Get Taxonomy record in wc REST API | |
function s9_product_get_callback($post, $attr, $request, $object_type) { | |
$terms = array(); | |
// Get terms | |
foreach (wp_get_post_terms( $post[ 'id' ],'customtax') as $term) { | |
$terms[] = array( | |
'id' => $term->term_id, | |
'name' => $term->name, | |
'slug' => $term->slug, | |
'custom_field_name' => get_term_meta($term->term_id, 'custom_field_name', true) | |
); | |
} | |
return $terms; | |
} | |
//Update Taxonomy record in wc REST API | |
function s9_product_update_callback($values, $post, $attr, $request, $object_type) { | |
// Post ID | |
$postId = $post->get_id(); | |
//Example: $values = [2,4,3]; | |
// Set terms | |
wp_set_object_terms( $postId, $values , 'customtax'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment