Last active
July 18, 2022 19:49
-
-
Save brandonjp/21fed6266453de7ba76b3d2bc0e5a06f to your computer and use it in GitHub Desktop.
PHP - Wordpress Metabox.io ajax fetch custom taxonomy metadata
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
/** | |
// ------------------------- | |
// Fetch Taxonomy Term & Meta | |
// ------------------------- | |
// GOAL: When a user selects a taxonomy term (from a MetaBox.io field) this helps fetch | |
// the term & it's metadata and returns JSON so the JS can load it into a Custom HTML block | |
// ------------------------- | |
// FORUM - https://metabox.io/support/topic/show-data-from-related-post-term-after-selection/ | |
// PHP - https://gist.github.com/21fed6266453de7ba76b3d2bc0e5a06f | |
// JS - https://gist.github.com/3b636d0c7e55ce6dc58ceba3de9a974e | |
// ------------------------- | |
**/ | |
// Gets meta data for a term and returns JSON | |
function get_json_term_meta() | |
{ | |
global $wpdb; | |
$termID = isset($_GET['termID']) ? $_GET['termID'] : false; | |
$field = isset($_GET['field']) ? $_GET['field'] : false; | |
if (!empty($termID)) { | |
if (empty($field)) { | |
$data = get_term_meta($termID); | |
$term = get_term($termID); | |
// add the term name | |
$data['term_name'] = [$term->name]; | |
if (!empty($data['related_customer'])) { | |
$relCustomer = get_term($data['related_customer'][0]); | |
// add the customer name | |
$data['related_customer_name'] = [$relCustomer->name]; | |
} | |
} else { | |
$data = get_term_meta($termID, $field); | |
} | |
echo wp_send_json($data); | |
} | |
wp_die(); | |
} | |
add_action('wp_ajax_get_json_term_meta', 'get_json_term_meta'); | |
// Gets a term and returns JSON | |
function get_json_term() | |
{ | |
global $wpdb; | |
$termID = isset($_GET['termID']) ? $_GET['termID'] : false; | |
$field = isset($_GET['field']) ? $_GET['field'] : false; | |
if (!empty($termID)) { | |
if (empty($field)) { | |
$data = get_term($termID); | |
} else { | |
$data = get_term($termID, $field); | |
} | |
echo wp_send_json($data); | |
} | |
wp_die(); | |
} | |
add_action('wp_ajax_get_json_term', 'get_json_term'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment