WordPress have some official way to check request method?

Viewed 1350

I'm creating an plugin with admin panel to save configurations, and the url from <form action="url" method="post"> is the same to show the panel, what's I need check request method type, I need call the save function, if request type is POST then to show the panel.

Currently I'm using this way to check:

if($_SERVER['REQUEST_METHOD'] === 'POST') { }

So my code is like this:

add_action('admin_menu', 'menu');

function menu() {
  add_menu_page('MyPlugin', 'manage_options', 'menu_item_id', 'load_page');
}

function load_page() {
  if($_SERVER['REQUEST_METHOD'] === 'POST') {
    // call the save function.
  }
  // print admin panel HTML here.
}

I just wondering if this is the best way in WP resolve the problem, because seems not elegante for me.

WordPress have some official way to check request method or not? Or should I send form request to another URL instead, and redirect to original page after save the data?

1 Answers

I did not see an official way of handling this, but phpcs does complain about direct use of super globals like $_SERVER and seems to be happy with:

if ( 'POST' !== filter_input( INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_STRING ) ) {
    // Do something.
}
Related