0

I am struggling with a coding problem as we want to guide the user to the next unread post within a category ('puzzles'), since we don't want users to go back and re-submit old puzzles to game their metrics. Anytime the user accesses this category, we want to automatically send her to next puzzle post she hasn't answered.

To do this, I track the post ID of the last puzzle each user submitted in their user meta. I've been trying to change my category-specific single post template to automatically detect if the user has submitted any puzzles, if so retrieve the post ID of the last puzzle they submitted, and redirect them to the next post in the category, if not direct them to the first post in the category. Tearing my hair out over this code today, so hope someone smart and kind can guide me where I've gone wrong. What I've done so far just puts me in endless re-direct loop until I get 'too many redirects' error.

    // Find out what the first post in the puzzles category is
    $args = array(
        'category_name' => 'puzzles',
        'showposts' => 1,
        'fields' => 'ids',
        'post_type' => 'post',
        'post_status' => 'published',
        'orderby' => 'date',
        'order' => 'ASC'
    );
    $posts = get_posts( $args );
    $firstQ = $posts[0];

    // Find out if the user has done any puzzles before
    $lastQ = get_user_meta( $user_id, 'cs-pzl-lastQ', TRUE );
    if (!$lastQ) {
        // User has never done a puzzle, so send user to  first post in Daily Puzzle category
        wp_redirect( get_page_link($firstQ) );
        exit;
    } else {
        // Send user to the next Q after the last one they did
        if ($lastQ == get_the_ID()) {
            $nextQ = get_next_post( TRUE );
            wp_redirect( get_page_link($nextQ) );
            exit;
        } else {
            // Send user to lastQ post, figure out what is the next Q in the puzzle sequence, and re-direct to it
                wp_redirect( get_page_link($lastQ) );
                exit; 
        }
    }

If anyone can spot my blunder - or tell me a simpler way to accomplish the desired outcome - I'll be very, very grateful...

1 Answer 1

0

I've found the error in my nested if statements which was causing the infinite redirect loop - I failed to check if we were already on the first post before redirecting to the first post in the category. Duh!? It really had nothing to do with how I was using get_posts or wp_redirect...

Need more coffee >-(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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