Skip to content

Instantly share code, notes, and snippets.

@leurdo
Created December 10, 2020 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leurdo/65c51612e73129191ae88d637b738d34 to your computer and use it in GitHub Desktop.
Save leurdo/65c51612e73129191ae88d637b738d34 to your computer and use it in GitHub Desktop.
Get taxonomy by term and keep it in transient
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