Looped back and forward links for CPT taxonomy posts in WordPress

I have a WordPress website for a client with a Custom Post Type with a requirement for its single Post type pages to have a static Back and Next link in it but I can’t figure it out for the life of me!

I’m still a newbie in PHP coding, please be patient with me.

Read More

Help!

Below is the code I found that works closely to what I need to accomplish except for a few things:

a. I need both Back and Forward links to be visible at the very first page and very last page of the CPT taxonomy (‘books’).

Let’s say we have 6 pages of Books CPT. Taxonomy is “new books”.

With the code I have right now, both links do show up on the first page (1st page) and last (6th page) but only the Back page link in the first Post page would have a link class, and only the Next page link in the last page would have a link class. The pages in the middle (2nd-5th pages) would have the links both showing up minus the link class, meaning just plain text.

b. I need the back and forward links to have a link class. I tried to do this code but it doesn’t work:

add_filter('next_post_link_attributes', 'nextbookbutton');
add_filter('previous_post_link_attributes', 'prevbookbutton');

function previousbookbutton() {
    return 'class="back-button"';
}

function nextbookbutton() {
    return 'class="forward-button"';
}

c. This is the code I have inside single-books.php template

<?php 

if( get_adjacent_post(false, '', true) ) { 
    previous_post_link('%link', 'Back');
} else { 
    $first = new WP_Query('posts_per_page=1&order=ASC&post_type=new-books'); $first->last_post();
        echo '<a href="' . get_permalink() . '" class="back-button"></a>';
    wp_reset_query();
}; ?>


            <h2 id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h2>


<?php   
if( get_adjacent_post(false, '', false) ) { 
    next_post_link('%link', 'Next');
} else { 
    $last = new WP_Query('posts_per_page=1&order=DESC&post_type=new-books'); $last->the_post();
        echo '<a href="' . get_permalink() . '" class="forward-button">Next Post &rarr;</a>';
    wp_reset_query();
}; ?>

d. To give a basic idea of the look I’m trying to achieve, the end should look like this

< Page Name >

Left and right arrows would be the Back and Forward buttons to go through the other posts within the taxonomy of this Custom Post Type.

Thanks to anyone who could provide guidance and help to fix this.

Related posts