Home › Forums › General Issues › How to use WP Term Meta, the easy way! › Reply To: How to use WP Term Meta, the easy way!
Thanks Edir, you’ve inspired me to write a more general version.
This version is based on “post_id” provided by ACF, which is actually an ACF-post_id (not a real wp_posts table ID)
and also based on get_field()
documentation, which is pretty steady in ACF-post_id formats.
(Dis)advantage: uses global variable for taxonomy caching.
//returns BOOLEAN false or a term id (int)
$GLOBALS['taxonomies_for_acf_term_meta_filter'] = [];
function my_acf_get_term_id_from_acf_post_id( $acf_post_id ){
if( is_numeric($acf_post_id) ) return false; //not a special ID...
if( empty($GLOBALS['taxonomies_for_acf_filter']) )
$GLOBALS['taxonomies_for_acf_filter'] = get_taxonomies();
$taxonomies = &$GLOBALS['taxonomies_for_acf_filter']; //shorthand
$term_id = 0;
foreach( $taxonomies as $taxonomy ){
//special id is in format somestring_ID
$term_id = str_replace( $taxonomy.'_', '', $acf_post_id );
//If not numeric at all, or something is removed while cast type to int (must use "!=" !!!!!)
//=> not a proper ID... => nothing to do here...
if( ! is_numeric($term_id) || ( ((int)$term_id) != $term_id ) ) continue;
$term_id = (int)$term_id;
break;
}
if( $term_id < 1 ) return false; //not a proper ID...
return $term_id;
}
function my_acf_update_term_meta($value, $post_id, $field) {
//FILTER! ===> MUST ALWAYS RETURN $value !
$term_id = my_acf_get_term_id_from_acf_post_id( $post_id );
if( $term_id === false ) return $value; //not a proper ID... MUST USE "===" !!!!!
update_term_meta($term_id, $field['name'], $value);
return $value;
}
add_filter('acf/update_value', 'my_acf_update_term_meta', 10, 3);
add_filter('acf/update_value', 'my_acf_update_term_meta', 10, 3);
function my_acf_load_term_meta($value, $post_id, $field) {
//FILTER! ===> MUST ALWAYS RETURN $value !
$term_id = my_acf_get_term_id_from_acf_post_id( $post_id );
if( $term_id === false ) return $value; //not a proper ID... MUST USE "===" !!!!!
$value = get_term_meta($term_id, $field['name'], true);
return $value;
}
add_filter('acf/load_value', 'my_acf_load_term_meta', 10, 3);
add_filter('acf/load_value', 'my_acf_load_term_meta', 10, 3);
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.