Skip to content

Instantly share code, notes, and snippets.

@hellofromtonya
Created July 20, 2017 15:50
Show Gist options
  • Save hellofromtonya/b8c8382a76b82a040ddb425374aab5fb to your computer and use it in GitHub Desktop.
Save hellofromtonya/b8c8382a76b82a040ddb425374aab5fb to your computer and use it in GitHub Desktop.
Walk the term metadata to get a specific value
<?php
/**
* Get the specified metadata value for the term or from
* one of it's parent terms.
*
* @since 1.0.0
*
* @param WP_Term $term Term object
* @param string $meta_key The meta key to retrieve.
*
* @return mixed|null
*/
function get_hierarchichal_term_metadata( WP_Term $term, $meta_key ) {
if ( ! is_taxonomy_hierarchical( $term->taxonomy ) ) {
return;
}
if ( ! has_parent_term( $term ) ) {
return;
}
return get_term_metadata_recursively( $term, $meta_key );
}
/**
* Recursively get the term metadata by the specified meta key.
*
* This function walks up the term hierarchical tree, searching for
* a valid metadata value for the given meta key.
*
* The recursive action stops when:
* 1. The current term level has the metadata value.
* 2. The current term level does not have a parent term.
*
* @since 1.0.0
*
* @param WP_Term $term Term object
* @param string $meta_key The meta key to retrieve.
* @param mixed|null $meta
*
* @return mixed|null
*/
function get_term_metadata_recursively( WP_Term $term, $meta_key, $meta = null ) {
$meta = get_term_meta( $term->term_id, $meta_key, true );
if ( $meta ) {
return $meta;
}
if ( ! has_parent_term( $term ) ) {
return $meta;
}
// Get the parent term
$parent_term = get_term_by( 'id', $term->parent, $term->taxonomy );
if ( $parent_term === false ) {
return $meta;
}
// Try again
return get_term_metadata_recursively( $parent_term, $meta_key, $meta );
}
/**
* Checks if the term has a parent.
*
* @since 1.0.0
*
* @param WP_Term $term Term object.
*
* @return bool
*/
function has_parent_term( WP_Term $term ) {
return ( $term->parent > 0 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment