get_next_posts_link not working without parameter max_num_pages

I have a custom search page (searchpage.php) using pagination, and I am tring to add lines like below dynamically to my header.php inside head/head tag for better pagination SEO.

link rel="prev" href="https://www.example.com/search/cats/page/2/"
link rel="next" href="https://www.example.com/search/cats/page/4/"

While doing this, I have used below code mentioned here in functions.php.

?php
function rel_next_prev(){
    global $paged;    
    if ( get_previous_posts_link() ) { ?
        link rel="prev" href="?php echo get_pagenum_link( $paged - 1 ); ?" /?php
    }    
    if ( get_next_posts_link() ) { ?
        link rel="next" href="?php echo get_pagenum_link( $paged +1 ); ?" /?php
    }    
}
add_action( 'wp_head', 'rel_next_prev' );
?

get_previous_posts_link() works fine, but get_next_posts_link doesn't work, after some investigation I believe it requires max_num_pages parameter to work.

Now I am not able to get max_num_pages because it is in searchpage.php.

Topic paginate-links functions pagination seo Wordpress

Category Web


I spent the night working on the same issue. What I did was.

<?php
function rel_next_prev(){
    global $paged;
    $default_posts_per_page = get_option( 'posts_per_page' );

    if ( get_previous_posts_link() ) { ?>
        <link rel="prev" href="<?php echo get_pagenum_link( $paged - 1 ); ?>" /><?php
    }    
    if ( get_next_posts_link(null,$default_posts_per_page) ) { ?>
        <link rel="next" href="<?php echo get_pagenum_link( $paged +1 ); ?>" /><?php
    }    
}
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
add_action( 'wp_head', 'rel_next_prev' );
?>

It's imperative to pass arguments on get_next_posts_link, first one null, and the second one an int, just use get_option( 'posts_per_page' ), it has to be different than 0 and it works on the search page as well.

I hope everyone looking for the same issue read this.


Try to use this to get max_num_pages in searchpage.php

global $wp_query;
$wp_query->max_num_pages;

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.