WordPress: la funzione in_category e la gestione delle categorie discendenti

WordPress: la funzione in_category e la gestione delle categorie discendenti

La funzione di WordPress in_category() verifica se un post appartiene ad una data categoria. Può essere usato sia nel Loop che al di fuori di esso. Per impostazione predefinita, questa funzione non può gestire la gerarchia delle categorie (ma, come vedremo, è possibile trovare una soluzione). Vediamone i dettagli.

Sintassi e uso


<?php in_category( $category, $post ) ?>

Parametri

$category
I valori possono essere l'ID della categoria, il nome, lo slug o, se sono più valori, un array di questi ultimi.
$post
Facoltativo. Può essere l'ID del post e per impostazione predefinita fa riferimento al post corrente nel Loop o nella query.

Valore di ritorno

Booleano: true se il post appartiene a quella categoria, altrimenti false.

Esempi


if(in_category('jquery')) {

	//...

} else {

	//...

}

Gestire la gerarchia delle categorie

Il team di WordPress propone questa soluzione per testare se un post è in una categoria discendente:


/**
 * Tests if any of a post's assigned categories are descendants of target categories
 *
 * @param int|array $cats The target categories. Integer ID or array of integer IDs
 * @param int|object $_post The post. Omit to test the current post in the Loop or main query
 * @return bool True if at least 1 of the post's categories is a descendant of any of the target categories
 * @see get_term_by() You can get a category by name or slug, then pass ID to this function
 * @uses get_term_children() Passes $cats
 * @uses in_category() Passes $_post (can be empty)
 * @version 2.7
 * @link http://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category
 */
if (! function_exists( 'post_is_in_descendant_category' ) ) {
	function post_is_in_descendant_category( $cats, $_post = null ) {
		foreach ( (array) $cats as $cat ) {
			// get_term_children() accepts integer ID only
			$descendants = get_term_children( (int) $cat, 'category' );
			if ( $descendants && in_category( $descendants, $_post ) )
				return true;
		}
		return false;
	}
}

Esempio:


if ( in_category( 'fruit' ) || post_is_in_descendant_category( 11 ) ) {
	//...
}

oppure:


post_is_in_descendant_category( get_term_by( 'name', 'fruit', 'category' ) )
Torna su