Search code examples
phpwordpresscategories

This there a smarter way to use php next/previous_post?


I have a Next/Previous button on my blog, which works great when you start viewing from the homepage and going backwards (in order going back or forward through posts). I use this:

<div><h4><span><?php next_post('% &lsaquo;&lsaquo;&lsaquo;',  'Previous', 'no', 'no'); ?></span>
 <span> <div class="right"><?php previous_post('&rsaquo;&rsaquo;&rsaquo;  %', 'Next', 'no', 'no'); ?></span>
 </h4></div>

However, every post is split into categories and I have a menu for every category...this is when i run into problems. I use the above code in the single.php, but when you click on a post within its category and click next/previous...it goes to the next or previous post which was posted at the time of that particular post...not category.

Is it possible to do the following: if the user visits and continues browsing the ste normally (viewinng the posts in the order I posted them) then the next/previous buttons work as normal, but if user is browsing via a category, the next and previous buttons will know this and take the user through the rest of those post?


Solution

  • It might be possible that you just append a parameter to the URL if the user comes from the front page. So you had:

    http://path.to/blog/article/url/?fromhome=true

    and could check it when you call the previous_post method. If it is set, you can modify its parameters so it displays all posts, otherwise you would display only posts from the same category. (Don't forget to pass the fromhome parameter to the next/previous post links!)

    Edit: You can use the post_link filter to modify the links in the permalink/next_post methods.