skip to Main Content

I am making a WordPress plugin that allows users to create a post on the frontend and then automatically redirects them to the post they just created. I have to use two separate functions and a session variable to achieve this because wp_redirect can’t be used after the header has been sent. The issue that I am running in to is the session variable is not sending the permalink for the post that was just created and is instead sending the previous post’s permalink.

The function below is initialized when the user submits a form

function create_post(){
    
if(is_user_logged_in())
{
    if(isset($_POST['ispost']))
    {
     
        global $current_user;
        get_currentuserinfo();

        $user_login = $current_user->user_login;
        $user_email = $current_user->user_email;
        $user_firstname = $current_user->user_firstname;
        $user_lastname = $current_user->user_lastname;
        $user_id = $current_user->ID;

        $post_title = $_POST['title'];
        $sample_image = $_FILES['sample_image']['name'];
        $post_content = $_POST['sample_content'];
        $category = $_POST['category'];

        $new_post = array(
            'post_title' => $post_title,
            'post_content' =>$post_content,
            'post_status' => 'publish',
            'post_type' => $post_type,
            'post_category' => $category
        );
    
        $pid = wp_insert_post($new_post);
        add_post_meta($pid, 'meta_key', true);
       $_SESSION['pid'] = get_post_field( 'post_name', $pid );
        if (!function_exists('wp_generate_attachment_metadata'))
        {
            require_once(ABSPATH . "wp-admin" . '/includes/image.php');
            require_once(ABSPATH . "wp-admin" . '/includes/file.php');
            require_once(ABSPATH . "wp-admin" . '/includes/media.php');
        }
        if ($_FILES)
        {
            foreach ($_FILES as $file => $array)
            {
                if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK)
                {
                    return "upload error : " . $_FILES[$file]['error'];
                }
                $attach_id = media_handle_upload( $file, $pid );
            }
        }
        if ($attach_id > 0)
        {
            //and if you want to set that image as Post then use:
            update_post_meta($pid, '_thumbnail_id', $attach_id);
            $_SESSION['pid'] = $pid->post_name;
            
        }

        $my_post1 = get_post($attach_id);
        $my_post2 = get_post($pid);
        $my_post = array_merge($my_post1, $my_post2);
        
        
    }
    

}
else
{
    echo "<h2 style='text-align:center;'>User must be login for add post!</h2>";
}
}

and this function is supposed to redirect the user to the post that was just created on init

add_action('init', 'myInit');
function myInit() {
    if (isset($_POST['ispost'])) {
        $errors = myFormValidation();
        if (empty($errors)) {
            
           // echo get_permalink($pid);
            $url = 'https://somethingsomething.com/'. $_SESSION['pid'];
            wp_redirect($url);
            

          
        }
        //Set the errors here
    }
}

How can I make $_SESSION[‘pid’] send the current post’s permalink and not the previous one?

2

Answers


  1. Chosen as BEST ANSWER

    I ended up creating session variables for all of the inputs and then creating the post after the linked page loads and it worked. I then used JavaScript to redirect to the newly created post.

    if(is_user_logged_in())
    {
        if(isset($_POST['ispost']))
        {
            global $current_user;
            get_currentuserinfo();
    
            $user_login = $current_user->user_login;
            $user_email = $current_user->user_email;
            $user_firstname = $current_user->user_firstname;
            $user_lastname = $current_user->user_lastname;
            $user_id = $current_user->ID;
    
    
            $_SESSION['post_title']=$_POST['title'];
            $_SESSION['sample_image']=$_FILES['sample_image']['name'];
            $_SESSION['post_content']=$_POST['sample_content'] . do_shortcode('[wpstream_go_live]'); 
            // do_shortcode('[wpstream_go_live id="12"]'); 
            $_SESSION['post_category']=$_POST['category'];
    
            //$post_title = $_POST['title'];
            //$sample_image = $_FILES['sample_image']['name'];
            //$post_content = $_POST['sample_content'];
            //$category = $_POST['category'];
        }
    }
    
    
    add_action('loop_end', 'myInit');
    function myInit() {
        if (isset($_POST['ispost'])) {
            $errors = myFormValidation();
            if (empty($errors)) {
                echo $_SESSION['post_title'];
                    $new_post = array(
                    'post_title' => $_SESSION['post_title'],
                    'post_content' => $_SESSION['post_content'] . $_SESSION['post_category'],
                    'post_status' => 'publish',
                    'post_type' => $post_type,
                    'post_category' =>array($_SESSION['post_category']) 
                );
    
                $pid = wp_insert_post($new_post);
                add_post_meta($pid, 'meta_key', true);
                
                $url= get_permalink($pid);
                echo '<script type="text/javascript">';
                //echo 'alert("' . $pid . '")';
                echo 'window.location = "' . $url . '"';
                echo '</script>';    
                
                //echo do_shortcode('[wpstream_go_live id="12"]');
                
                $_SESSION['pid'] = $pid;
                $url= "www.google.com";
            
                if (!function_exists('wp_generate_attachment_metadata'))
                {
                    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
                    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
                    require_once(ABSPATH . "wp-admin" . '/includes/media.php');
                }
    
                if ($_FILES)
                {
                    foreach ($_FILES as $file => $array)
                    {
                        if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK)
                        {
                            return "upload error : " . $_FILES[$file]['error'];
                        }
                        $attach_id = media_handle_upload( $file, $pid );
                    }
                }
                
                if ($attach_id > 0)
                {
                    //and if you want to set that image as Post then use:
                    update_post_meta($pid, '_thumbnail_id', $attach_id);
                    $_SESSION['pid'] = $pid;
                    
                }
        
                $my_post1 = get_post($attach_id);
                $my_post2 = get_post($pid);
                $my_post = array_merge($my_post1, $my_post2);
            }
        } else {
            echo "<h2 style='text-align:center;'>User must be login for add post!</h2>";
            //echo do_shortcode('[wpstream_go_live id="12"]');
            echo PLUGIN_DIR;
        }
    }
    

  2. Probably the redirection is going to the wrong place because the myInit() function runs before the create_post() function.

    wp_redirect

    You need to add exit() immediately after the call to wp_redirect(); or you will have unexpected results.

    To Redirect the User

    You could do the following.

    1. Try to process the form before the headers are sent and use wp_redirect() to redirect the user.

    I guess this would work in theory, but probably it’s not ideal since I assume the create_post() function is being handled with an admin_post_(action) hook which runs after the headers are sent.

    or

    1. Use JavaScript to redirect the user after the headers are sent.

    You can redirect the user after processing the form by using JavaScript.

    echo '<script type="text/javascript">';
    echo 'window.location = "' . $url . '"';
    echo '</script>';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search