Perform a redirect after user action

Is it possible to redirect a user in WP without the header/wp_redirect being before header()?

I have a plugin that allows users to manage content they have created on the site… for example, they can delete it or disable comments

It’s quite basic so i’m just using a GET request.. ie.

?action=comments&status=disable

When this button is click the action is performed but nothing happens on the page and the url is now: www.domain.com/user_data?action=comments&status=disable what I want to do is on success redirect the user back to www.domain.com/user_data

I have tried wp_redirect() and header() but they give ‘headers already sent warnings’

I’m not sure how i can put that before the header when this code is within my plugin.

    $query = $this->db->update(
      //do something
    );

    if($query == 0)
    {
      $this->setMessage('error', 'There was an error: ' . $this->db->print_error());
    }
    else
    {
      wp_redirect(site_url('/user_data/'));
    }

2 Answers
2

It may not be the correct approach, but I found that using wp_loaded does the trick and puts you back in the right spot; you have to set the right conditions to be sure the correct data is being handled. Then strip the url from the conditions before redirecting. Aside from condtions you can also apply capability checks.

add_action ('wp_loaded', 'clean_admin_referer');
function clean_admin_referer() {

if ( isset( $_REQUEST['condition1']) && isset($_REQUEST['condition2']) ) {

    if (current_user_can('administrator')) {

        <!-- do your database magic -->

        $_SERVER['REQUEST_URI'] = remove_query_arg( array( 'condition1', 'condition2' ));

        wp_redirect($_SERVER['REQUEST_URI']);

    }
}

Leave a Comment