Search code examples
phpwordpresspostpermalinkstestimonials

Wordpress How to give previous and next post link from same taxonomy?


I have post type testimonials.

I am listing that testimonials by specific taxonomy with read more link.

When user click on read more link which is get_permalink( $post ), and redirect to specific page then i want to show previous and next post link with same taxonomy of current post?

If you require any more info then let me know.

I have added true as third element for it, but don't worked

previous_post_link( '%link', '<span class="meta-nav">' . _x( '&larr;', 'Previous post link', 'twentytwelve' ) . '</span> %title' ,true );

Solution

  • Refer this Link

    I found solution as below

    Go your single.php file

    // Only for Testimonial
    
    if(get_post_type( $post )=="wpm-testimonial")
    {
    
        $terms = array_shift(get_the_terms($post->ID, 'wpm-testimonial-category'));
    
    
        // get_posts in same custom taxonomy
        $postlist_args = array(
            'posts_per_page'  => -1,
            'orderby'         => 'ID title',
            'order'           => 'ASC',
            'post_type'       => 'wpm-testimonial',
            $terms->taxonomy  => $terms->slug
        );
    
        $postlist = get_posts( $postlist_args );
    
        // get ids of posts retrieved from get_posts
        $ids = array();
        foreach ($postlist as $thepost) {
            $ids[] = $thepost->ID;
        }
    
        // get and echo previous and next post in the same taxonomy
        $thisindex  = array_search($post->ID, $ids);
        $previd     = $ids[$thisindex-1];
        $nextid     = $ids[$thisindex+1];
    
        ?>
        <nav class="nav-single">
        <?php
    
            if ( !empty($nextid) ) {
    
                echo '<span class="nav-previous"><a rel="next" href="' . get_permalink($nextid). '">Previous</a></span>';
    
            }
    
            if ( !empty($previd) ) {
    
        echo '<span class="nav-next"><a rel="prev" href="' . get_permalink($previd). '">Next</a></span>';
    
            }
    
        ?>
        </nav><!-- .nav-single -->
    
        <?php
    }else{
    
        // Your Default Previous/Next Links in single.php file
    }
    ?>