0

I have a basic WordPress code that redirects someone to the last post type created on the site, in this case is the "case" post type:

    <?php 
/*
Template Name: Redirect
*/

$args = array(
    'posts_per_page' => '1',
    'post_type' => 'case'
);
$post = get_posts($args);
if($post){
    $url = get_permalink($post[0]->ID);
    wp_redirect( $url, 301 ); 
    exit;
}

I'm trying to expand on this code so I redirect people to their own created posts only, so they will be redirected to the last post they created with an added parameter like ?mode=edit to the end of the url and if they're not logged in, they are going to be sent to a pre-defined error page, like domain.com/error.

I'm a bit new to PHP and for the life of me, I can't figure it out. Any input or hints are appreciated.

1 Answer 1

0

Here's the modified code to achieve this:

<?php
/*
Template Name: Redirect
*/

// Check if the user is logged in
if (is_user_logged_in()) {
    // Get the current user's ID
    $user_id = get_current_user_id();

    // Query for the last post created by the user in the "case" post type
    $args = array(
        'posts_per_page' => 1,
        'post_type' => 'case',
        'author' => $user_id,
        'orderby' => 'date',
        'order' => 'DESC',
    );
    $posts = get_posts($args);

    if (!empty($posts)) {
        // Get the last post created by the user
        $post = $posts[0];

        // Construct the redirect URL with the "?mode=edit" parameter
        $url = get_permalink($post->ID) . '?mode=edit';

        // Redirect the user
        wp_redirect($url, 301);
        exit;
    } else {
        // Redirect the user to a predefined error page
        wp_redirect('http://yourdomain.com/error', 301);
        exit;
    }
} else {
    // Redirect the user to a predefined error page since they are not logged in
    wp_redirect('http://yourdomain.com/error', 301);
    exit;
}
?>

In this code, we first check if the user is logged in using is_user_logged_in(). If the user is logged in, we proceed to query the last post created by the user in the "case" post type and construct the redirect URL. If the user is not logged in, we redirect them to the predefined error page.

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.