开发者

Wordpress plugin admin redirect and returning errors

开发者 https://www.devze.com 2023-04-11 23:01 出处:网络
Apologies, but I did ask this at the wordpress site but it doesn\'t seem to get viewed yet alone answered! Hope I\'m not breaking any rules by reposting here.

Apologies, but I did ask this at the wordpress site but it doesn't seem to get viewed yet alone answered! Hope I'm not breaking any rules by reposting here.

I've been developing a wordpress plugin that has an admin section with a form to add and edit various things. Now after an admin submits the form I wanted to redirect if successful (to show updated values) or show the various error messages if not. I got the header errors from trying wp_redirect and after looking through SO I started to use the add_action method so I could redirect without header error messages. The problem I have now though is that my array of errors is now always null, even if the form wasn't submitted correctly. I have defined the errors variable before add_action and in the function in add_action I have

   global $errors;

If I do a var_dump of $errors in the function that handles the submit it is populated, but then on my actual page it is always empty. My guess is that I'm not familiar with the o开发者_开发问答rder the pages get called in WP and I'm missing something, but how does anyone else handle this?

  //the index.php for pluging
  //require necessary files
  $errors = null;
  include('plugin_file.php');
  //Tie into wordpress hooks
  add_action('widgets_init', 'plugin::register_func');
  add_action('admin_menu', 'plugin::add_menu_item');
  add_action('admin_init', 'plugin::check_form_submission');

Then the form submission is similar to

  //THE Class file for my plugin
  static function check_form_submission(){
  global $errors;
        if(empty($_POST['some_field'])){
                      $errors['some-error'] = 'some error';
        }
  if(!$errors){
    //handle and redirect here
   }else{
  var_dump($errors); // does have values
  }
  }

In the actual admin page that shows the form

  //actual admin page that shows in WP
  var_dump($errors); // returns NULL

will always be null even if it has values above. Anyone got any advice how to handle this? I'm new to WP plugin development so not sure what the best practice is.


well it looks like I worked this out.

On the actual admin page I need to declare my $errors array as global as well

global $errors;

I guess wordpress must somehow box the admin page into a function and so the $errors array was not referencing the global var.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号