Come ottenere l'ID della categoria in single.php WordPress?

22 dic 2012, 13:24:07
Visualizzazioni: 32.4K
Voti: 2

Ho bisogno di ottenere l'id della categoria in single.php. Ho provato questo:
$cat_ID = get_query_var('cat');

Non ha funzionato. Cosa dovrei usare invece?

0
Tutte le risposte alla domanda 2
0

Utilizza wp_get_post_categories()

Recupera l'elenco delle categorie per un articolo.

<?php wp_get_post_categories( $post_id, $args ) ?>

Tieni presente che la funzione restituisce un array (di ID delle categorie) anche se hai solo una categoria nel tuo articolo.

L'esempio seguente mostra come vengono recuperate le categorie e poi vengono ottenute ulteriori informazioni per ogni categoria.

$post_categories = wp_get_post_categories( $post_id );
$cats = array();

foreach($post_categories as $c){
    $cat = get_category( $c );
    $cats[] = array( 'name' => $cat->name, 'slug' => $cat->slug );
}

Riferimento: http://codex.wordpress.org/Function_Reference/wp_get_post_categories

Un'Altra Opzione:

Utilizza get_the_terms();

<?php
    $id = get_the_id();
    $terms = get_the_terms( $id, 'category' );
    // print_r( $terms );
    foreach($terms as $term) {
        echo $term->cat_ID;   
    }
?>
22 dic 2012 14:39:08
1

Puoi semplicemente utilizzare

$categories = get_the_category();

per ottenere le categorie assegnate.

22 dic 2012 13:40:39
Commenti