July 7, 2020
WordPress: Add Rel Prev Next Meta Tags For Custom Query Loop
When we use custom query loop in wordpress, we lose SEO befenits such as the rel prev/next meta tags that’s in the <head> and improves how Google reads our website.
This code will read the custom query pagination and will display those tags in the head section of the pages.
Paste this into your theme’s functions.php and edit the following attributes:
-
- Instead of “22” (the first “if”) – change to your custom blog page.
- “posts_per_page” is now “10”. Change this number according to your posts_per_page pagination links in your custom blog page.
- (Optional) If our custom query reads another post type but the regular “post”, change the “post_type” parameter to your cpt name instead of “post”.
add_action( 'wp_head', 'rel_next_prev' ); function rel_next_prev(){ global $paged; if ( get_the_ID() == 22 ) { $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $data= new WP_Query(array( 'post_type'=>'post', // your post type name 'posts_per_page' => 10, // post per page 'paged' => $paged, )); if($data->have_posts()) { $total_pages = $data->max_num_pages; if ($total_pages > 1){ $current_page = max(1, get_query_var('paged')); } if ($total_pages > $paged) { $next_num = $paged + 1; } if ($paged > 1) { $prev_num = $paged - 1; } if ( $prev_num ) { ?> <link rel="prev" href="<?php echo get_pagenum_link( $paged - 1 ); ?>" /> <?php } if ( $next_num ) { ?> <link rel="next" href="<?php echo get_pagenum_link( $paged +1 ); ?>" /> <?php } } } }