Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Get the specified metadata value for the term or from
  5. * one of it's parent terms.
  6. *
  7. * @since 1.0.0
  8. *
  9. * @param WP_Term $term Term object
  10. * @param string $meta_key The meta key to retrieve.
  11. *
  12. * @return mixed|null
  13. */
  14. function get_hierarchichal_term_metadata( WP_Term $term, $meta_key ) {
  15.  
  16. if ( ! is_taxonomy_hierarchical( $term->taxonomy ) ) {
  17. return;
  18. }
  19.  
  20. if ( ! has_parent_term( $term ) ) {
  21. return;
  22. }
  23.  
  24. return get_term_metadata_recursively( $term, $meta_key );
  25. }
  26.  
  27. /**
  28. * Recursively get the term metadata by the specified meta key.
  29. *
  30. * This function walks up the term hierarchical tree, searching for
  31. * a valid metadata value for the given meta key.
  32. *
  33. * The recursive action stops when:
  34. * 1. The current term level has the metadata value.
  35. * 2. The current term level does not have a parent term.
  36. *
  37. * @since 1.0.0
  38. *
  39. * @param WP_Term $term Term object
  40. * @param string $meta_key The meta key to retrieve.
  41. * @param mixed|null $meta
  42. *
  43. * @return mixed|null
  44. */
  45. function get_term_metadata_recursively( WP_Term $term, $meta_key, $meta = null ) {
  46. $meta = get_term_meta( $term->term_id, $meta_key, true );
  47. if ( $meta ) {
  48. return $meta;
  49. }
  50.  
  51. if ( ! has_parent_term( $term ) ) {
  52. return $meta;
  53. }
  54.  
  55. // Get the parent term
  56. $parent_term = get_term_by( 'id', $term->parent, $term->taxonomy );
  57. if ( $parent_term === false ) {
  58. return $meta;
  59. }
  60.  
  61. // Try again
  62. return get_term_metadata_recursively( $parent_term, $meta_key, $meta );
  63. }
  64.  
  65. /**
  66. * Checks if the term has a parent.
  67. *
  68. * @since 1.0.0
  69. *
  70. * @param WP_Term $term Term object.
  71. *
  72. * @return bool
  73. */
  74. function has_parent_term( WP_Term $term ) {
  75. return ( $term->parent > 0 );
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement