How do I get the next page of posts link?

Functions such as get_next_posts_link allow you to get the HTML link to the next page, with few parameters for change (label and max pages). I want to get the URL to the next page so I can add custom classes to the link.

Related posts

Leave a Reply

2 comments

  1. Why build the link yourself, when you can just add the class to the result of get_next_posts_link()?

    add_filter('next_posts_link_attributes','example_add_next_link_class');
    function example_add_next_link_class($attr) {
      return $attr . ' class="example-class"';
    }
    

    Now the link sent back by get_next_posts_link() will have your class in it.

  2. While a lot of common functions can be found on the WordPress Codex, there are also still undocumented functions in the source code.

    The previous_posts function is one such function, which is documented in the source:

    Display or return the previous posts page link.

    Using previous_posts(false), we can get the previous page’s URL, without displaying.

    However this doesn’t check for when there are no more pages, and will return 404s if used on it’s own.

    Inspecting the source of get_next_posts_link, we can use the code for checking if we have reached the page boundary, and return just the link:

    /**
     * Gets the next posts link, checked against whether the page exists or not
     *
     * Returns the link or null if it doesn't exist
     */
    function get_next_posts_url($max_page = 0) {
        global $paged, $wp_query;
    
        if ( !$max_page )
            $max_page = $wp_query->max_num_pages;
    
        if ( !$paged )
            $paged = 1;
    
        $nextpage = intval($paged) + 1;
    
        if ( !is_single() && ( $nextpage <= $max_page ) ) {
            return next_posts( $max_page, false );
        }
    }