WordPress.org

Ready to get started?Download WordPress

Forums

How to display prev/next category on post? (2 posts)

  1. endlessstudio
    Member
    Posted 1 year ago #

    Goal
    I wan to display previous / next category name on post.

    Example
    Category1 Category 2 Category 3
    Post 1 Post 4 Post 7
    Post 2 Post 5 Post 8
    Post 3 Post 6

    Let say I have a data like this and went to post 5.
    I want to detect what category the post 5 is then calculate +, - and display the Category 1 name and Category 3 name.

  2. endlessstudio
    Member
    Posted 1 year ago #

    Able to figure it out.

    <?php
        $categories = get_the_category();
        $separator = ' ';
        $output = '';
        if($categories){
            foreach($categories as $category) {
                $prev_step .= '<a href="'.get_category_link( $category->term_id-1 ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" class="previous-step">'.get_cat_name( $category->term_id-1 ).'</a>'.$separator;
                $next_step .= '<a href="'.get_category_link( $category->term_id+1 ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" class="next-step">'.get_cat_name( $category->term_id+1 ).'</a>'.$separator;
    		}
    	}
    ?>
    
    <?php echo trim($prev_step, $separator);?>
    <?php echo trim($next_step, $separator);?>

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags