John Davidson

php - WordPress Infinite Loop on Single Post

0 comments
Message:


I've taken some code from https://gist.github.com/banago/5603826 so that I am able to do previous/next posts for a specific post on my WordPress site which is a custom post type of 'product'.


<?php 
if( get_adjacent_post(false, '', true) ) {
previous_post_link('%link', '&larr; Previous Post');
} else {
$first = new WP_Query('post_type=products&posts_per_page=1&order=DESC'); $first->the_post();
echo '<a href="' . get_permalink() . '">&larr; Previous Post</a>';
wp_reset_query();
};

if( get_adjacent_post(false, '', false) ) {
next_post_link('%link', 'Next Post &rarr;');
} else {
$last = new WP_Query('post_type=products&posts_per_page=1&order=ASC'); $last->the_post();
echo '<a href="' . get_permalink() . '">Next Post &rarr;</a>';
wp_reset_query();
};

?>


However it doesn't actually infinitely loop, if it's on the first or last post, the link outputs the page it's already on. An example can be found here - http://s860623395.websitehome.co.uk/products/bespoke-build/


Any solutions to this? Thanks!



My Answer:
However, when I implement the code on my single-product.php template file, I am encountering an infinite loop issue where the page keeps refreshing and never stops.

To fix this issue, you can try adding a condition to check if the current post is the same as the previous or next post before displaying the links. Here's an example of how you can modify the code:

php
$prev_post = get_previous_post();
$next_post = get_next_post();

if ($prev_post && $prev_post->ID !== get_the_ID()) {
echo 'Previous Post';
}

if ($next_post && $next_post->ID !== get_the_ID()) {
echo 'Next Post';
}
?>


By adding the condition `$prev_post->ID !== get_the_ID()` and `$next_post->ID !== get_the_ID()`, you are ensuring that the previous and next posts are not the same as the current post, which should prevent the infinite loop issue.

Make sure to replace the code in your single-product.php template file with the modified code above and see if it resolves the issue.

Rate this post

3 of 5 based on 3880 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us