• Hi guys,
    how can I get category slug of next and prev posts?

    thanks for your answers 😉

    (my apology for my english)

    • This topic was modified 6 years, 9 months ago by xochipi.
Viewing 1 replies (of 1 total)
  • Place this code in your functions.php:

    function adjacent_post_by_category( $category, $direction, $content ) {
    
        // Info
        $postIDs = array();
        $currentPost = get_the_ID();
    
        // Get posts based on category
        $postArray = get_posts( array(
    
            'category' => $category,
            'orderby'=>'post_date',
            'order'=> 'DESC'
    
        ) );
    
        // Get post IDs
        foreach ( $postArray as $thepost ):
    
            $postIDs[] = $thepost->ID;
    
        endforeach;
    
        // Get prev and next post ID
        $currentIndex = array_search( $currentPost, $postIDs );
        $prevID = $postIDs[ $currentIndex - 1 ];
        $nextID = $postIDs[ $currentIndex + 1 ];
    
        // Return information
        if( $direction == 'next' AND $nextID ):
    
            return '<a rel="next" href="' . get_permalink( $nextID ) . '">' . $content . '</a>';
    
        elseif( $direction == 'prev' AND $prevID ):
    
            return '<a rel="prev" href="' . get_permalink( $prevID ) . '">' . $content . '</a>';
    
        else:
    
            return false;
    
        endif;
    
    }

    —————-

    And this as your prev/next links (function parameters are examples):

    <?php echo adjacent_post_by_category( 10, 'prev', 'Show previous post' ); ?>
    
    <?php echo adjacent_post_by_category( 10, 'next', 'Show next post' ); ?>

    —————-

    Regards
    Louis
    https://wemanageyoursite.com/

Viewing 1 replies (of 1 total)
  • The topic ‘How get the category slug of adjacent posts’ is closed to new replies.