Web Hosting
  1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

WordPress fix Reply To: How get the category slug of adjacent posts

Discussion in 'Misc WordPress Requests' started by louiswol94, Nov 9, 2017.

  1. louiswol94

    Guest

    Reply To: How get the category slug of adjacent posts, by louiswol94

    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/

    Reply To: How get the category slug of adjacent posts
     
    #1

Share This Page

Web Hosting