【问题标题】:Wordpress - get categories only from current postWordpress - 仅从当前帖子中获取类别
【发布时间】:2017-07-22 16:08:47
【问题描述】:

我想在 single.php 仅显示当前帖子中的类别。我正在使用此代码,但它显示了所有正在使用的类别......我该怎么办?

<nav class="post-navigation">
<?php $args = array(
     "hide_empty" => 1,
     "type"      => "post",      
     "orderby"   => "name",
     "order"     => "ASC" );
     $categories = get_categories( $args );
    foreach ( $categories as $category ) {
        echo ' <a href="' . get_category_link( $category->term_id ) . '">' . $category->name . '</a>';}
?>
</nav>

【问题讨论】:

  • 您是否尝试将其包装在标准的 wordpress 循环中?

标签: php wordpress post categories


【解决方案1】:

相信你想使用get_the_category()

$categories = get_the_category();
$separator = ' ';
$output = '';
if ( ! empty( $categories ) ) {
foreach( $categories as $category ) {
    $output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
echo trim( $output, $separator );
}

Documentation

【讨论】:

  • 我更改了我的代码,现在,我得到了这个:codepen.io/anon/pen/gmrwrd 此仅显示活动帖子的类别 :) 但我想更改顺序以使其像这样“主类别 > 子类别” > 帖子标题”并通过 id 禁用某些类别,如何做到这一点?编辑:我现在看到你的代码,如何在你的代码中做到这一点?
  • 不做一些测试,我不确定。试着研究一下,看看你能不能想出点什么。如果您遇到另一个问题,您可以随时提交另一个问题。同时,如果此答案已解决您的原始问题,请单击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
猜你喜欢
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-21
  • 2011-05-16
  • 2014-11-18
相关资源
最近更新 更多