I recently converted some old WordPress code over to using the admin-post.php mechanism.

add_action( 'admin_post_myaction', function(){
    //...my code to do stuff here...

    //redirect back to the main page
    $url = menu_page_url( 'my_original_menu_item', false );
    wp_safe_redirect( $url );    

} );

As you can see in the above simplified code sample, once I'm done handling my post, I grab the URL for my original menu item and redirect the user back to the page they came from.

However -- this isn't working. The menu_page_url does not return a menu URL. When I investigated this, I discovered the global $_parent_pages; variable that menu_page_url relies on was empty. I was able to fix this my invoking the admin_menu hook

do_action( 'admin_menu', '' ); 
$url = menu_page_url( 'my_original_menu_item', false );
wp_safe_redirect( $url );  

but this leaves me with a few questions.

  1. Is the above (no loaded menus on an admin-post.php request) standard system behavior? Or is there something else that might be wrong with my system?

  2. What systems do and don't load during a request to admin-post.php? (possibly huge question, pointers appreciated)

  3. Is the above pattern (post to admin-post.php, redirect back using menu_page_url considered an OK WordPress practice, or am I misusing admin-post.php?

Experienced programmer here -- I'm just trying to map WordPress concepts onto things I'm familiar with from web-MVC frameworks.

1 Answer 1

  1. When using admin-post.php, no loaded menus on an admin-post.php request is standard wordpress behavior. Standard practise to redirect after processing done on post action hook is to use: wp_redirect( admin_url( 'admin.php?page=YOUR_PAGE' ) );

  2. When using admin-post.php, wordpress will include wp-admin/includes/wp-admin.php instead of wp-admin/wp-admin.php ( Wordpress Admin Bootstrap ) to skip some setup. One of the API call skipped in this included files is menu build files.

    During Wordpress Admin Bootstrap, system includes menu.php which eventually fire actions to load and build admin menus. Post action intentionally skipped menu loads processing.

  3. For plugins and forms, post to adin-post.php is considered correct and after processing use wp_redirect with admin_url to redirect page to original menu item page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.