Get the name of the first category

三世轮回 提交于 2021-02-18 22:46:29

问题


I am trying to create a single page that lists the content of each category. I have managed to create the list. I now need to get the name of the category. I have the following code:

<ul>
    <li> CATEGORY NAME HERE </li>

    <?php query_posts('cat=0'); ?>
    <?php while ( have_posts() ) : the_post(); ?>
        <li>
            <a href="<?php echo get_permalink(); ?>">
            <?php the_title(); ?></a>
        </li>
    <?php endwhile; ?>
</ul>

How to call the name of the first category (0)?

Current edit: Why won't multiple works?

<div class="first-col">
    <ul>
        <?php query_posts('cat=0'); ?>
        <?php while ( have_posts() ) : the_post(); ?>

        <li> <?php $category = get_the_category(); 
        echo $category[0]->cat_name;
        ?> </li>
        <li>
            <a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a>
        </li>
        <?php endwhile; ?>
    </ul>
</div>

<div class="first-col">
    <ul>
        <li> <?php $category = get_the_category(); 
        echo $category[0]->cat_name;?> </li>

        <?php query_posts('cat=3'); ?>
        <?php while ( have_posts() ) : the_post(); ?>
            <li>
                <a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a>
            </li>
        <?php endwhile; ?>

    </ul>
</div>

回答1:


You have to get the array of categories and echo the first one from the array. http://codex.wordpress.org/Function_Reference/get_the_category

<?php
$category = get_the_category(); 
echo $category[0]->cat_name;
?>



回答2:


According to wordpress developers codex:

    $categories = get_the_category();
if ( ! empty( $categories ) ) {
    echo '<a href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a>';
}

This will give you the first category and also link it to that category's page.




回答3:


there is also a shortcodes plug in that will help create lists based on categories, terms, etc. http://wordpress.org/plugins/display-posts-shortcode/



来源:https://stackoverflow.com/questions/18536091/get-the-name-of-the-first-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!