1

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.

  • 2
    You need to run your custom query before wp_head runs. – Milo Aug 16 '17 at 13:00
  • @Milo please write it as answer, and I'll accept it. Moving my custom query before get_header(); fixed the problem. – HOY Aug 17 '17 at 12:26
0

Try to use this to get max_num_pages in searchpage.php

global $wp_query;
$wp_query->max_num_pages;
  • Did you mean using your code in functions.php ?, when I use your code in functions php, and echo $wp_query->max_num_pages; it prints 0 to page. – HOY Aug 16 '17 at 9:25
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.