1

I am new to WordPress development and trying to display an admin notice if the user omits needed fields when saving a custom post. When they didn't display, I realized there is a redirect happening so moved the code into my init() method, where the idea was to check if a hidden input is set (indicating a save), and then checking whether to display. After some debugging, I've found myself in a really confusing situation. If I simply put in the line

add_action('admin_notices', 'image_error');

the admin notice displays as expected, every time. If I put it in a trivial if statement:

if (true) {
  add_action('admin_notices', 'image_error');
}

also works as expected. However, if I try to following block of code, the admin notice is not displayed:

$flag_worked = isset($_POST['post_saved']);
if ($flag_worked) {
    $dumb = 1;
    add_action('admin_notices', 'image_error');
}

Stepping through with the debugger confirms that $flag_worked is indeed true, the code block is entered, $dumb is set to one, and the add_action line is executed. Yet the notice doesn't display, when this statement should essentially evaluate the same as the if (true) experiment. I'm clearly misunderstanding something fundamental, can anyone explain my error and how I might go about correcting it? Why is the notice not displaying when the line to add it is being hit? I feel like I'm taking crazy pills.

2

The add_action function only adds the action to a queue, which will be executed when the corresponding do_action is called. So, when you queue it too late, nothing will happen.

To know for sure what happens in your case, you must carefully examine the order of the hook execution. That requires insight in your complete setup, including plugins and so on.

My guess is that by the time isset($_POST['post_saved']) is true do_action ('admin_notices') is already executed and queueing something for it is useless.

The way to solve this is not to add the action conditionally. Always add the action and put the test inside the function. Like this:

add_action('admin_notices', 'image_error');
function image_error () {
  $flag_worked = isset($_POST['post_saved']);
  if ($flag_worked) {
    echo 'error';
    }
  • That did the trick, I'll be sure to stay more mindful of timing issues such as this in the future. Thanks so much for getting me back on track! – swilkeni Mar 23 '17 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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