2013-06-25 27 views
5

E 'possibile ottenere il nome di categoria di una categoria dato l'ID postale, il seguente codice funziona per ottenere l'ID di categoria, ma come posso ottenere il nome?Ottieni il nome della categoria dall'ID post

<?php $post_categories = wp_get_post_categories(4); echo $post_categories[0]?> 

Grazie!

risposta

16

qui si va get_the_category($post->ID); tornerà la serie di categorie di quel post è necessario scorrere l'array

$category_detail=get_the_category('4');//$post->ID 
foreach($category_detail as $cd){ 
echo $cd->cat_name; 
} 

get_the_category

+0

grazie, ma dove devo definire l'ID post in quel codice, che voglio il nome della categoria di. – user1937021

+0

vedi la mia risposta modificata –

+0

Non mi piace come si debba iterare sull'array per ottenere il nome ma funziona. – Radmation

0

Utilizzare la funzione get_the_category().

$post_categories = wp_get_post_categories(4); 
$categories = get_the_category($post_categories[0]); 
var_dump($categories); 
+0

cool, ma come faccio a eco il risultato? – user1937021

+0

@ user1937021 hai controllato l'uscita ?? – swapnesh

+0

yes @swapnesh l'output mi dà questo array (0) {} – user1937021

5

non lo fa

<?php get_the_category($id) ?> 

fare solo quello, dentro il ciclo?

per l'esterno:

<?php 
global $post; 
$categories = get_the_category($post->ID); 
var_dump($categories); 
?> 
+0

Che restituisce un array per me - non il nome della categoria – Radmation

1
function wp_get_post_categories($post_id = 0, $args = array()) 
{ 
    $post_id = (int) $post_id; 
    $defaults = array('fields' => 'ids'); 
    $args = wp_parse_args($args, $defaults); 
    $cats = wp_get_object_terms($post_id, 'category', $args); 

    return $cats; 
} 

Ecco il secondo argomento della funzione wp_get_post_categories() che è possibile passare gli attributi di ricezione dei dati.

$category_detail = get_the_category('4',array('fields' => 'names')); //$post->ID 
foreach($category_detail as $cd) 
{ 
    echo $cd->name; 
} 
8
echo '<p>'. get_the_category($id)[0]->name .'</p>'; 

è quello che forse cercando.

+0

GRAZIE !! Esattamente ciò di cui avevo bisogno - niente loop - molto più carino – Radmation

+0

Grazie ... Restituisce il nome della categoria di post su quale post siamo – TusharG

+0

è davvero buono, se non è necessario utilizzare il ciclo, ad es. nel modello di un singolo post. Bello. – Marek

0
 <?php 
    // in woocommerce.php 
    $cat = get_queried_object(); 
    $cat->term_id; 
    $cat->name; 
    ?> 

    <?php 
    // get product cat image 
     if (is_product_category()){ 
      $cat = get_queried_object(); 
      $thumbnail_id = get_woocommerce_term_meta($cat->term_id, 'thumbnail_id', true); 
      $image = wp_get_attachment_url($thumbnail_id); 
      if ($image) { 
       echo '<img src="' . $image . '" alt="" />'; 
      }  
} 
?> 
Problemi correlati