admin_notices action doesn’t trigger within save_post action

Question

After the save_post action runs, I’m attempting to also use the admin_notices action and it doesn’t work. What am I doing wrong?

If I move the admin_notices action into the constructor, it works fine (of course it shows for every page in the admin which isn’t desired). I’m assuming it must be the logical sequence of the hooks or the nesting itself?

Code sample:

if (!class_exists('CPTToPDF')) {

  // FPDF library
  require_once(plugin_dir_path(__FILE__) . 'fpdf182/fpdf.php');

  class CPTToPDF {
    private $pdf;

    public function __construct() {
      add_action('save_post', array($this, 'render_to_pdf'));
    }

    public function render_to_pdf() {
      //die('Render to PDF running...');
      $this->pdf = new FPDF();
      add_action('admin_notices', array($this, 'admin_notice__success'));
    }

    public function admin_notice__success() {
      //die('Admin notice running...');
      echo '<div class="notice notice-success is-dismissable">CPTToPDF: Saved post.</div>';
    }

    public function admin_notice__error() {
      echo '<div class="notice notice-error is-dismissable">CPTToPDF: Did not save post.</div>';
    }
  }

}

I placed the initial hook into save_post in the plugin’s constructor method. That works fine (if I uncomment the die('Render to PDF running...'); line it does die and display that message, so I know my callback works.

However, this second action/hook doesn’t fire properly inside of the render_to_pdf callback:
add_action('admin_notices', array($this, 'admin_notice__success'));

Even if I uncomment the die('Admin notice running...'); I get no output when a post is saved and new page is reloaded (other than the default “Page Updated. View Page” admin notice). So the nested action doesn’t seem to be working and I’m not sure why.

0
, , , armadadrive 2 years 2020-06-10T12:10:19-05:00 0 Answers 110 views 0

Leave an answer

Browse
Browse