Search code examples
phpwordpresspaginationposts

Conditionally alter next_posts_link() / previous_posts_link() in Wordpress


I have an archive template I'm working on, and at the bottom of the page I'm using

<?php next_posts_link("&laquo; Older Posts", $wp_query->max_num_pages); ?>
<?php previous_posts_link("Newer Posts &raquo;", $wp_query->max_num_pages); ?>

to display the pagination.

These functions, it seems, check whether or not there are newer/older posts to display, and conditionally determines whether or not to display the prev/next links.

The behavior I am trying to achieve is that if there are not older/newer posts to be displayed on a given page, That an anchor tag is still created, but not given an href attribute and given a separate class.

i.e. - on a page that contains the most recent posts, I want to show

<a class="previous-posts" href="THE_PREVIOUS_POSTS_PAGE">&laquo; Older Posts</a>
<a class="next-posts disabled">Newer Posts &raquo;</a>

instead of just an "Older Posts" link with nothing next to it (for layout reasons).

Any ideas about either where I can edit the behavior of the default functions or how I can craft my own?

UPDATE:

Mike Lewis' answer was perfect for Next_posts, but I still seem to have messed up previous_posts.

<?php if ($prev_url = previous_posts($wp_query->max_num_pages, false)){
    // next_posts url was found, create link with this url:
    ?><a href="<?= $prev_url ?>">&laquo; Newer Posts</a><?php
} else {
    // url was not found, do your alternative link here
    ?><a class="disabled">&laquo; Newer Posts</a><?php
} ?>

<?php if ($next_url = next_posts($wp_query->max_num_pages, false)){
    // next_posts url was found, create link with this url:
    ?><a href="<?= $next_url ?>">Older Posts &raquo; </a><?php
} else {
    // url was not found, do your alternative link here
    ?><a class="disabled">Older Posts &raquo; </a><?php
} ?>

The first function always displays the disabled link, while the second behaves exactly as expected. Any idea what's up here?


Solution

  • This was tricky. If you look at the core code for the previous and next_posts_link() functions, you'll find next_posts() and previous_posts(). These are in /wp-includes/link-template.php around line 1552.

    If you use next_posts($wp_query->max_num_pages, false), the second paramater is $echo, which we don't want, so we can check the value:

    if ($next_url = next_posts($wp_query->max_num_pages, false)){
        // next_posts url was found, create link with this url:
        ?><a href="<?= $next_url ?>">Next Posts</a><?php
    } else {
        // url was not found, do your alternative link here
        ?><a href="#" class="disabled">Next Posts</a><?php
    }
    

    EDIT: previous_posts($echo = true) takes one parameter, so in this case:

    previous_posts(false).