Last active
October 14, 2019 20:05
-
-
Save brandonjp/3b636d0c7e55ce6dc58ceba3de9a974e to your computer and use it in GitHub Desktop.
JS - 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 fetches the | |
// term & it's metadata and loads 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 | |
// ------------------------- | |
// fetch taxonomy metadata and load it into view | |
let get_job_tax_html = function get_job_tax_html(tax) { | |
let htmlField = `.${tax}_html`; | |
jQuery(`${htmlField}`).slideUp(); | |
// jQuery(`${htmlField}`).addClass('hidden'); | |
jQuery(`${htmlField} .rwmb-input > *`).empty(); | |
let termID = jQuery('#' + tax).val(); | |
if (termID !== '') { | |
let data = { | |
action: 'get_json_term_meta', | |
termID: termID | |
}; | |
let jqReq = jQuery.get(ajaxurl, data); | |
jqReq.done(function(response) { | |
// console.log(tax, response); | |
jQuery.each(response, function(key, val) { | |
// use this on first run to create the HTML to place inside the Custom HTML field | |
// jQuery(`<span class="${key}">${val[0]}</span>`).appendTo(`${htmlField} .rwmb-input`); | |
// as long as html structure is in place, this will inject the matching data | |
if (val.length) jQuery(`${htmlField} .rwmb-input .${key}`).text(val[0]); | |
}); | |
// jQuery(`${htmlField}`).removeClass('hidden'); | |
jQuery(`${htmlField}`).slideDown(); | |
}); | |
} | |
} | |
// PM - fetch term meta on init & then again on change | |
get_job_tax_html('job_pm_taxonomy'); | |
jQuery('select#job_pm_taxonomy').change(function() { | |
get_job_tax_html('job_pm_taxonomy'); | |
}); | |
// Contact - fetch term meta on init & then again on change | |
get_job_tax_html('job_contact_taxonomy'); | |
jQuery('select#job_contact_taxonomy').change(function() { | |
get_job_tax_html('job_contact_taxonomy'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment