WordPress.org

Make WordPress Core

Opened 3 years ago

Closed 3 years ago

Last modified 3 years ago

#37679 closed defect (bug) (duplicate)

Actions that remove and add themselves again, break other actions

Reported by: noplanman Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: General Keywords:
Focuses: Cc:

Description

Scenario:
I have 2 actions for save_post with priorities 11 and 12, let's call them sp11 and sp12.

sp11 gets called before sp12, which is correct.

Now, if sp11 removes itself via remove_action and then adds itself again via add_action, sp12 is never called, BUT instead, sp11 is called again, so twice in total!

I've dug into the code a bit and found the problem:
This happens because the $wp_filters['save_post'] array gets reordered and the call list isn't correct any more.

The problem happens in the last loop of do_action here.

Because the loop is using pointers, when an item is removed and re-added, the pointer is wrong if the items have changed their original position.

For my example above, when sp11 gets removed and added again, it gets added to the end of the array, thus skipping over sp12 and calling sp11 again.

To help visualise what happens (simplified):

// Loop starts, current (first) element.
$wp_filters['save_post'] => [
  11 => 'sp11', //pointer here
  12 => 'sp12',
];

-> execute sp11

// After remove_action and add_action in sp11.
$wp_filters['save_post'] => [
  12 => 'sp12', //pointer here
  11 => 'sp11',
];
// Next element.
$wp_filters['save_post'] => [
  12 => 'sp12',
  11 => 'sp11', //pointer here
];

-> execute sp11

Change History (3)

#1 @swissspidy
3 years ago

  • Keywords do_action add_action remove_action loop removed
  • Severity changed from major to normal
  • Version trunk deleted

Related: #17817

#2 @noplanman
3 years ago

  • Resolution set to duplicate
  • Status changed from new to closed

Duplicate of #17817.

Didn't find that one, thanks for linking it.

Really hope this gets fixed soon, as it's been an issue since 2011.

#3 @swissspidy
3 years ago

  • Milestone Awaiting Review deleted

@noplanman The issue is way older than 5 years though :-) It's currently slated for the 4.7 milestone, so chances are high it might finally get in.

Note: See TracTickets for help on using tickets.