dr_bonzo
dr_bonzo

Reputation: 213

How to redirect to different admin page in Wordpress?

I am writing a Wordpress plugin.

I want to perform a redirect (after creating DB records from POST data, etc...) to other ADMIN page.

Neither header("Location: ...) nor wp_redirect() work - i get

Warning: Cannot modify header information - headers already sent by

which comes from obvious reason.

How do I properly perform a redirect in a Wordpress?

Upvotes: 10

Views: 22854

Answers (7)

WraithKenny
WraithKenny

Reputation: 1041

For a link added with add_submenu_page (or related function), use the returned $hook_suffix to add an action to "load-$hook_suffix" and do the redirect there. This is how you hook to the page load before the output has begun.

Upvotes: 2

codecowboy
codecowboy

Reputation: 10095

On your form action, add 'noheader=true' to the action URL. This will prevent the headers for the admin area from being outputted before your redirect. For example:

<form name="post" action="<?php echo admin_url('admin.php?page=your-admin-page&noheader=true'); ?>" method="post" id="post">

Upvotes: 40

zero_padded
zero_padded

Reputation: 133

If you still want to redirect from your plugin admin page to another admin page while using WP add_page* functions then, after processing your request, you can just echo something like this:

<script type="text/javascript">
window.location = '/whatever_page.php';
</script>

This just renders a javascript based redirect to "/whatever_page.php" thus ensuring no trouble with headers already sent by WP as Chris Ballance already said.

Change "/whatever_page.php" to something like "/wp-admin/admin.php?page=whatever_page"

Upvotes: 4

Andy
Andy

Reputation: 3171

Load it into template_redirect.

add_action('template_redirect', 'myplugin_template_redirect');

function myplugin_template_redirect() {  
   wp_redirect('http://www.example.com/', 301);
}

Upvotes: -1

dr_bonzo
dr_bonzo

Reputation: 213

I think I was doing it the wrong way.

My code was inside a add_menu_page() inside add_action('admin_menu', ...) call

which is probably called later during the request (after page header has been created and displayed).

Moving my code outside of my plugin handles, into main scope worked - it needs some cleanup, and fixes, but redirect works.

Anyway, thanks for the answers.

Upvotes: 1

Chris Ballance
Chris Ballance

Reputation: 34337

You need to make sure that nothing is sent to http output before the redirect takes place.

You can set "window.location('newlocation');" and that will still let you redirect after output has been sent to the browser.

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319531

I suppose you just have to make sure that wp_redirect() comes before any output has been sent.

Upvotes: 0

Related Questions