In one of my plugin's shortcode I'm handing user login / registration on the fly with a post submission. So the whole thing is happening within the shortcode like:
<?php
function this_shortcode() {
ob_start();
//if isset(login)... process login, get $user_id
//else if isset(registration)... process registration, get $user_id
//else if already registered, get $current_user->ID as $user_id
/**
* if !empty($user_id){
* $p_id = wp_insert_post();
* if !empty($p_id) {
* echo success;
* **I NEED ONLY WHEN THE REDIRECTION SHOULD TAKE PLACE**
* } else {
* echo error;
* }
* } else {
* }
*/
<form>
<!-- registration/login + post insertion form here -->
</form>
return ob_get_clean();
}
add_shortcode( 'my-shortcode', 'this_shortcode' );
I've already learnt that, wp_redirect()
is not the right way to redirect from shortcode. So, what I'm trying is:
function project_registration_login_redirection(){
global $post;
if( has_shortcode( $post->post_content, 'my-shortcode' ) ) {
if ( isset( $_POST['my_submit'] ) ) {
wp_redirect( home_url('/that-page') );
exit();
}
}
}
add_action( 'template_redirect', 'project_registration_login_redirection' );
But it's clear that, this one redirects without any check, even though the form validation is showing error there, and the wp_insert_post()
is returning empty.
How can I process the form somewhere, but do the redirection only when the form returns a valid feedback?
I tried:
global $post, $p_id;
if ( isset( $_POST['my_submit'] ) && !empty( $p_id ) ) {
but it's not working.
template_redirect
and nothing but markup output should happen in the shortcode handler. in your last snippet, it looks like you're trying to check$p_id
before it could ever possibly exist, if it's set in the shortcode handler.