Created
December 10, 2020 07:22
-
-
Save leurdo/65c51612e73129191ae88d637b738d34 to your computer and use it in GitHub Desktop.
Get taxonomy by term and keep it in transient
This file contains hidden or 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
public function get_tax_by_term($use_var) { | |
if ( ! $this->all_terms ) { | |
$this->all_terms = get_transient('all_terms_' . $this->post_type ); | |
if ( ! $this->all_terms ) { | |
$taxonomy_names = get_object_taxonomies( $this->post_type ); | |
$this->all_terms = []; | |
foreach ( $taxonomy_names as $taxonomy_name ) { | |
$terms = get_terms( [ | |
'taxonomy' => $taxonomy_name, | |
'hide_empty' => false, | |
'fields' => 'id=>slug', | |
] ); | |
$this->all_terms[ $taxonomy_name ] = $terms; | |
} | |
set_transient('all_terms_' . $this->post_type, $this->all_terms, DAY_IN_SECONDS ); | |
} | |
} | |
$tax = array_filter( $this->all_terms, function($element, $key) use ($use_var) { | |
if ( in_array( $use_var, $element ) ) { | |
return true; | |
} | |
return null; | |
}, ARRAY_FILTER_USE_BOTH ); | |
return $tax ? array_key_first($tax) : null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment