Creating a Back button on detail post page to go back to blog page with same query strings and page id

So, I would like to have a back button on the single post page that can be dynamic to the point to where it knows where it is in the query and bring me back to the blog page on the right page number and category and search query string. For example -> "localhost/news-blogs/page/3/?s=newsnb-cat=16" Now I can do this wp_get_referer() If was to stay on that page, but if I click on the next post link then it would just bring me back to the last page since wp_get_referer() fn just hold the last page history and if I was to keep clicking next post link it would need to know to change the page #, so when I clicked back it would bring me back to the page with that post exists.

Topic single pagination links query Wordpress

Category Web


So it looks like you can't get the page number unless you query the whole post type and query strings and then check that against how many pages you show on each page and then do some math to find what page that will be on, so I stuck with the next best thing. I kept the page number and echoed it along the post url and next and prev post links, so then I grab the number in the query string and echo it out on the back button.

// Get page number and set it

$getPageNumber = (get_query_var('paged')) ? get_query_var('paged') : 1;
$_GET['number'] = $getPageNumber;

// Post link

<?php
  the_permalink();
  if($_GET['nb-cat'] || $_GET['s']) echo '?';
  if($_GET['s']) echo 's=' . $_GET['s'];
  if($_GET['nb-cat'] && $_GET['s']) echo '&';
  if($_GET['nb-cat']) echo 'nb-cat=' . $_GET['nb-cat'];
  if(!isset($_GET['nb-cat']) && !isset($_GET['s'])) echo '?';
  if(isset($_GET['nb-cat']) || isset($_GET['s'])) echo '&';
  if($_GET['number']) echo 'number=' . $_GET['number'];
  ?>

// Back btn Link

<a href="/news-blogs/
 <?php
    if($_GET['number']) echo 'page/' . $_GET['number'];
    if($_GET['nb-cat'] || $_GET['s']) echo '?';
    if($_GET['s']) echo 's=' . $_GET['s'];
    if($_GET['nb-cat'] && $_GET['s']) echo '&';
    if($_GET['nb-cat']) echo 'nb-cat=' . $_GET['nb-cat'];
  ?> 
<a/>

// Next and Prev post Links

<?php if ( $prev != get_permalink() ) : ?>
  <a href="<?php echo $prev; if($_GET['number']) echo '?number=' . $_GET['number']; ?>" class="prev btn border padding">Prev</a>
<?php endif; ?>

<?php if ( $next != get_permalink() ) : ?>
  <a href="<?php echo $next; if($_GET['number']) echo '?number=' . $_GET['number']; ?>" class="next btn border padding">Next</a>
<?php endif; } ?>

About

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