Tag Archive for: categories

Dziś postanowiłem wyświetlić w jednym z projektów pewien banner, który miał się pokazać jedynie w określonej kategorii.

Ponieważ nie była to zwykła kategoria, lecz taksonomia, toteż musiałem nieco kombinować niż użyć zwykłej funkcji WP is_category.

 

Otóż mam taksonomię 'filmy’.

Struktura kategorii/termów w taksonomii 'filmy’ mam następujące:
– komedie
– – romantyczne
– – nieromantyczne
– thrillery
– sensacyjne

Dla wszystkich wpisów w kategorii komedie (razem podkategoriami) chcę wyświetlić banner.

Próbowałem z has_term, is_tax – bez skutku…

Poniższy kod ułatwił mi życie. W functions.php dodajemy:

//display something only in a certain term of taxonomy
function in_term($term,$taxonomy,$post_id=null) {
        if (has_term($term,$taxonomy,$post_id)) {
                return true;
        }
        $top_term = get_term_by('slug',$term,$taxonomy);
        if ($top_term) {               
                $children = get_term_children($top_term->term_id,$taxonomy );
                if (is_array($children) && !empty($children)) {
                        $post_terms = get_the_terms(get_the_ID(),$taxonomy);
                        foreach ($post_terms as $post_term) {
                                if (in_array($post_term->term_id, $children)) return true;
                        }
                }
        }
 
        return false;
}

Alternatywnie:

//display something only in a certain term of taxonomy
function in_term($term, $taxonomy, $post_id =null) {
        if ( null === $post_id ) {
              $post_id = get_the_ID();
        }
        if ( has_term($term, $taxonomy, $post_id) ) {
                return true;
        }

        $top_term = get_term_by('slug', $term, $taxonomy);
        if ( $top_term ) {               
                $children = get_term_children($top_term->term_id, $taxonomy );

                if (is_array($children) && !empty($children)) {
                        return has_term( $children, $taxonomy, $post_id );
                }
        }
 
        return false;
}

 

A w pliku, w którym chcemy wyświetlić element (np. single.php, sidebar.php) dodajemy:

 <?php if (in_term('komedie','filmy') ) { ?>
//tutaj wklejamy pożądaną treść	
		
 <?php } ?>

To rozwiązanie na szczęście obsługuje nie tylko obieżącego terma/kategorię, lecz także kategorie potomne.