如何从Get_the_Category获取类别URL?

时间:2016-03-07 作者:egr103

下面我的循环显示了与当前查看的帖子属于同一类别的最新4篇帖子。Its位于单个。php。

我正在尝试获取同一类别的URL,以便可以链接回该类别。php来查看来自同一类别的所有帖子。我原以为抓取类别slug会有用,但我下面的代码没有输出任何内容:

<?php
global $post;
$categories = get_the_category();

    foreach ($categories as $category) :

       $exclude = get_the_ID();
       $posts = get_posts(\'posts_per_page=4&category=\'. $category->term_id);

        foreach($posts as $post) :
         if( $exclude != get_the_ID() ) { ?>

                <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post c-1"> Link to actual post</a>

    <?php } endforeach; ?>

<a href="<?php bloginfo(\'url\'); ?>/categories/<?php echo $childcat->cat_slug; ?>" title="View all" class="btn border"><i class="i-right-double-arrow"></i> View all <?php echo $childcat->cat_slug; ?></a>
<?php  endforeach; wp_reset_postdata(); ?>

2 个回复
最合适的回答,由SO网友:Adam 整理而成

使用:

get_category_link( $category_id );
请参见:

https://codex.wordpress.org/Function_Reference/get_category_link

在您的具体情况下:

<?php
global $post;
$categories = get_the_category();

    foreach ($categories as $category) :

       $exclude = get_the_ID();
       $posts = get_posts(\'posts_per_page=4&category=\'. $category->term_id);

        foreach($posts as $post) :
         if( $exclude != get_the_ID() ) { ?>

                <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="post c-1"> Link to actual post</a>

    <?php } endforeach; ?>

<a href="<?php echo esc_url( get_category_link( $category->term_id ) ); ?>" title="View all" class="btn border"><i class="i-right-double-arrow"></i> View all <?php echo $category->name; ?></a>
<?php  endforeach; wp_reset_postdata(); ?>

SO网友:Mrbiizy

A STRAIGHT FORWARD AND CLEAN CODE

我是个新手:)

我修改了Adam给出的代码,删除了不需要回答初始问题的不必要部分。

It worked for me 100%.

试试看。

请让我知道它是否也适用于您:)

<?php $categories = get_the_category();
foreach ($categories as $category) :
endforeach; ?>

<a href="<?php echo esc_url( get_category_link( $category->term_id ) ); ?>">
  LINK TO CURRENT POST CATEGORY >>
</a>

<?php $categories = get_the_category();
foreach ($categories as $category) : ?>

The category is:
<a href="<?php echo esc_url( get_category_link( $category->term_id ) ); ?>">
  <?php echo $category->name; ?>
</a>

<?php endforeach; ?>
根据需要组合其他元素。玩玩吧,伙计。