WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a custom post type and used get_next_post() and get_previous_post() to create a simple pagination. However i need to create a pagination loop (if that is the correct term). If i'm on the first post i need to browse back to the last post and if i'm on the last post i need to browse to the first post. Is there a simple way to do this that i haven't seen but Google, this site and the codex has not been very helpfull :/

The current code i have is. I've tried to use wp_list_pages and other functions but with little luck.

$next_post = get_next_post();
$prev_post = get_previous_post();
$nav = array(
    "next_post" => array(
        "url"       => get_permalink($next_post->ID),
        "id"        => $next_post->ID,
        "titill"    => get_field("vinstri_titill", $next_post->ID)." - ".get_field("vinstri_undirtitill", $next_post->ID)
    "prev_post" => array(
        "url"       => get_permalink($prev_post->ID),
        "id"        => $prev_post->ID,
        "titill"    => get_field("vinstri_titill", $prev_post->ID)." - ".get_field("vinstri_undirtitill", $prev_post->ID)
share|improve this question
up vote 1 down vote accepted

Here is one idea for the previous post circle:

$next_post = get_next_post();
$prev_post = get_previous_post_circle();

where we have defined this function:

function get_previous_post_circle($in_same_cat = false, $excluded_categories = ''){
    $prev_post = get_previous_post($in_same_cat,$excluded_categories);
        return $prev_post;
        $prev_post = get_previous_post($in_same_cat,$excluded_categories);
            return $prev_post;
            return '';

and the filter function to remove the specific date comparison:

function custom_get_previous_post_where($where){
    $where=" WHERE ".implode(" AND ",array_slice(explode("AND",$where),1));
    return $where;

The aim is to emulate the get_previous_post() function with the same input parameters, but you could of course play with get_post() in your code instead to create the closed loop.

share|improve this answer
Genius! Works perfectly. Takk fyrir :) – dansige Mar 18 '13 at 21:46
Good luck with your project ... og bestu kveðjur norður ;-) – birgire Mar 19 '13 at 4:06

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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