Filtrar por categoría en single.php de WordPress

Las categorías se pueden filtrar por term_ids, nombres y slugs. Vemos unos ejemplos:

Para una publicación individual (generalmente manejada por la plantilla single.php), puedes probar las categorías de esa publicación incluso antes de que comience el bucle. Podrás usar esto para cambiar plantillas así:

if ( in_category('libros') ) {
    include 'single-libros.php';
} elseif ( in_category('cuadernos') ) {
    include 'single-cuadernos.php';
} else {
    // Continua con el Loop
    if ( have_posts() ) : while ( have_posts() ) : the_post();
    // ...
}

La prueba este in_category() dependiendo de la categoría de la publicación:

if ( in_category( 'libros' )) {
    // el_codigo...
} elseif ( in_category( array( 'literatura', 'ficcion' ) )) {
    // codigo_para_subcategorias...
} else {
    // etc.
}

Para verificar si una publicación está dentro de una categoría principal o cualquiera de sus subcategorías:

<?php
/**
 * Tests if any of a post's assigned categories are descendants of target categories
 *
 * @param int|array $categories 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)
 * @link originally at https://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category
 */
 
if ( ! function_exists( 'wpdocs_post_is_in_a_subcategory' ) ) {
function wpdocs_post_is_in_a_subcategory( $categories, $_post = null ) {
    foreach ( (array) $categories as $category ) {
        // get_term_children() only accepts integer ID
        $subcats = get_term_children( (int) $category, 'category' );
        if ( $subcats && in_category( $subcats, $_post ) )
            return true;
    }
    return false;
  }
}
?>

Úsalo para verificar si es single cat:

wpdocs_post_is_in_a_subcategory( 25 );

Úsalo para verificar si está dentro de una matriz de categorías principales o cualquiera de sus subcategorías:

wpdocs_post_is_in_a_subcategory( array( 25, 28, 124, 297, 298, 299 ) );