如何获得帖子类别

时间:2012-06-19 12:13:03

标签: wordpress

在主页我打印帖子,我想在foreach循环中打印类别名称?我怎么能这样做?

示例代码:

       if (have_posts()) : 

        $args = array(
            'showposts' => '5',
            'paged' => $paged
        );


        $thePosts = query_posts($args);

        foreach($thePosts as $post) : setup_postdata($post);

    ...

2 个答案:

答案 0 :(得分:1)

解决:

<?php

            GLOBAL $wpdb;

            $query = "
            SELECT 
                terms.slug, r.term_taxonomy_id, terms.name AS cat_name 
            FROM 

                {$wpdb->prefix}term_taxonomy t, {$wpdb->prefix}terms terms, $wpdb->posts p, $wpdb->term_relationships r 

            WHERE 

                t.term_id=terms.term_id AND 
                p.ID = r.object_id AND
                r.term_taxonomy_id = t.term_taxonomy_id AND 
                p.ID = '".$post->ID."'

            ORDER BY terms.term_order ASC, terms.term_id DESC";

            $categories = $wpdb->get_results($query, ARRAY_A);


            if(is_array($categories)){

                $i=1;
                foreach($categories as $category) { 

                    echo '<span>'.$category['cat_name'].'</span>';

                    ++$i;
                }#end foreach($categories 

            }#end if


            ?>

答案 1 :(得分:0)

将此代码放入循环中。

<?php
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list( __( ', ', 'twentyeleven' ) );

if ( '' != $categories_list ) {
$utility_text = __( 'This entry was posted in %1$s', 'twentyeleven' );
} 
printf( $utility_text );
?>

这将打印当前帖子的类别。希望你使用二十二岁的儿童主题。