简体   繁体   中英

Wordpress - get categories only from current post

I want to display the categories on single.php only from the current post . I'm using this code, but it displays all categories in use... What should I do?

<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>

Believe you want to be using 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 ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator;
}
echo trim( $output, $separator );
}

Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM