Skip to content

Don't fatal when invalid arguements are passed to wp_after_insert_post or after_delete_post. - #14356

Open
aaronjorbin wants to merge 5 commits into
WordPress:trunkfrom
aaronjorbin:followup/trac-64498/1
Open

aaronjorbin wants to merge 5 commits into
WordPress:trunkfrom
aaronjorbin:followup/trac-64498/1

Conversation

@aaronjorbin

Copy link
Copy Markdown
Member

Trac Ticket: https://core.trac.wordpress.org/ticket/64498#comment

Props bradshawtm

Use of AI Tools

AI assistance: Yes
Tool(s): Claude
Model(s): Fable 5.1
Used for: Initial code skeleton and test suggestions; final implementation and tests were reviewed and edited by me.


This Pull Request is for code review only. Please keep all other discussion in the Trac ticket. Do not merge this Pull Request. See GitHub Pull Requests for Code Review in the Core Handbook for more details.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

Core Committers: Use this line as a base for the props when committing in SVN:

Props jorbin, therssoftware, bradshawtm.

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

@github-actions

Copy link
Copy Markdown

Test using WordPress Playground

The changes in this pull request can previewed and tested using a WordPress Playground instance.

WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Some things to be aware of

  • All changes will be lost when closing a tab with a Playground instance.
  • All changes will be lost when refreshing the page.
  • A fresh instance is created each time the link below is clicked.
  • Every time this pull request is updated, a new ZIP file containing all changes is created. If changes are not reflected in the Playground instance,
    it's possible that the most recent build failed, or has not completed. Check the list of workflow runs to be sure.

For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation.

Test this pull request with WordPress Playground.

…ility

Cause: multisite hooks _update_posts_count_on_delete() onto after_delete_post too (src/wp-includes/ms-default-filters.php:78). It reads $post->post_status on string 'random' → warning → test error. Not our function's bug. Other core callbacks choking on junk are out of scope.

Fix: tests now call wp_random_content_flush_rewrite_rules_for_post() directly instead of do_action(). Isolates unit under test from unrelated callbacks on same hook. Data provider renamed data_invalid_arguments, test test_invalid_arguments_do_not_flush_rewrite_rules. Same five cases, now keyed by value shape rather than hook name. _doing_it_wrong() still asserted on every case.
@robelsust

Copy link
Copy Markdown

Thanks for working on this follow-up, @aaronjorbin! Removing the scalar and class type declarations on wp_random_content_flush_rewrite_rules_for_post() is definitely the right approach to prevent fatals when wp_after_insert_post or after_delete_post are triggered by third-party plugins.

Testing this locally revealed a critical edge case regarding default parameters and ArgumentCountError:

  1. ArgumentCountError on 1-argument after_delete_post calls:
    The after_delete_post action was introduced in WP 3.2.0 with only $post_id. The second parameter $post was only added in WP 5.5.0 (do_action( 'after_delete_post', $post_id, $post )). Third-party plugins still invoke do_action( 'after_delete_post', $post_id ) with a single argument.
    Because wp_random_content_flush_rewrite_rules_for_post( $post_id, $post, ... ) currently has no default for $post, any single-argument call still fatals:

    Fatal error: Uncaught ArgumentCountError: Too few arguments to function wp_random_content_flush_rewrite_rules_for_post(), 1 passed and at least 2 expected
    

    Providing defaults $post_id = 0, $post = null completely resolves this.

  2. Gracefully handling null === $post:
    When a caller fires do_action( 'after_delete_post', $post_id ) (or passes null), $post is null. Bailing with if ( null === $post ) { return; } before _doing_it_wrong() avoids firing false notices for valid legacy action invocations, while still preserving _doing_it_wrong() for genuinely invalid types (e.g. strings, arrays).

  3. Global variable placement:
    global $wp_rewrite; can be moved down immediately before its first usage on line 1582.

  4. Test coverage:
    Added test cases for single-argument and empty-argument calls to guarantee no ArgumentCountError can occur.

I've left inline code suggestions below for convenience!

…onal post parameter and improve error handling for invalid arguments

@robelsust robelsust left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing this so quickly, @aaronjorbin! Handling the fallback lookup via $post = get_post( (int) $post_id ) when $post is omitted and updating _update_posts_count_on_delete() in multisite cleanly resolves the ArgumentCountError regression. The test coverage is comprehensive and all CI checks pass.

Left a couple of minor notes/suggestions on the diff. Looks great!

Comment thread src/wp-includes/query.php
* @see WP_Rewrite::random_rewrite_rules()
* @global WP_Rewrite $wp_rewrite WordPress rewrite component.
*
* @param int $post_id Post ID.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* @param int $post_id Optional. Post ID. Default 0.
* @param WP_Post|null $post Optional. Post object. Default null.
* @param bool $update Optional. Whether this is an existing post being updated. Default false.
* @param WP_Post|null $post_before Optional. Post object before the update, null for new posts. Default null.
*/
function wp_random_content_flush_rewrite_rules_for_post( $post_id = 0, $post = null, $update = false, $post_before = null ): void {
if ( null === $post ) {
return;
}
if ( ! $post instanceof WP_Post ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: 1: $post, 2: WP_Post */
__( 'The %1$s argument must be a %2$s object.' ),
'<code>$post</code>',
'<code>WP_Post</code>'
),
'7.2.0'
);
return;
}
if ( null !== $post_before && ! $post_before instanceof WP_Post ) {
_doing_it_wrong(
__FUNCTION__,
sprintf(
/* translators: 1: $post_before, 2: WP_Post */
__( 'The %1$s argument must be a %2$s object or null.' ),
'<code>$post_before</code>',
'<code>WP_Post</code>'
),
'7.2.0'
);
$post_before = null;
}
global $wp_rewrite;
if ( ! $wp_rewrite->using_permalinks() || ! wp_is_random_content_redirect_enabled() ) {
return;
}

$this->assertSame( 0, $flushes->get_call_count(), 'Only pages and posts at the random base should flush the rewrite rules.' );
}

/**

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/**
/**
* Tests that missing or null post arguments (such as legacy after_delete_post calls with 1 argument)
* do not fatal, do not trigger doing_it_wrong, and do not flush rewrite rules.
*
* @dataProvider data_missing_or_null_post_arguments
*
* @param array $args The arguments to call the function with.
*/
public function test_missing_or_null_post_arguments_do_not_flush_rewrite_rules( array $args ): void {
$flushes = new MockAction();
add_filter( 'pre_update_option_rewrite_rules', array( $flushes, 'filter' ) );
wp_random_content_flush_rewrite_rules_for_post( ...$args );
$this->assertSame( 0, $flushes->get_call_count(), 'Missing or null arguments should not flush the rewrite rules.' );
}
/**
* Data provider for test_missing_or_null_post_arguments_do_not_flush_rewrite_rules.
*
* @return array<string, array{array}>
*/
public function data_missing_or_null_post_arguments(): array {
return array(
'single argument (legacy after_delete_post)' => array( array( 123 ) ),
'no arguments' => array( array() ),
'nulls' => array( array( null, null, false, null ) ),
'nulls without optional values' => array( array( null, null ) ),
);
}
/**
* @dataProvider data_invalid_arguments
*
* @param array $args The arguments to call the function with.
*/
public function test_invalid_arguments_do_not_flush_rewrite_rules( array $args ): void {
$this->setExpectedIncorrectUsage( 'wp_random_content_flush_rewrite_rules_for_post' );
$flushes = new MockAction();
add_filter( 'pre_update_option_rewrite_rules', array( $flushes, 'filter' ) );
wp_random_content_flush_rewrite_rules_for_post( ...$args );
$this->assertSame( 0, $flushes->get_call_count(), 'Invalid arguments should not flush the rewrite rules.' );
}
/**
* Data provider.
*
* Core never fires the `wp_after_insert_post` and `after_delete_post` actions with invalid
* arguments, but third-party code can. Doing so is incorrect usage and must not cause a
* fatal error.
*
* @return array<string, array{array}>
*/
public function data_invalid_arguments(): array {
return array(
'strings' => array( array( 'random', 'random', 'yes', 'random' ) ),
'arrays' => array( array( array(), array( 'post_name' => 'random' ), 1, array() ) ),
'strings without optional values' => array( array( 'random', 'random' ) ),
);
}

@tbradsha tbradsha left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your patience! I would probably just return early rather than doing a lookup if encountering an unexpected type. That'll allow it to handle it gracefully without the added complexity/overhead of a lookup.

But I'll defer to others more familiar with this code.

Comment thread src/wp-includes/ms-blogs.php Outdated
Co-authored-by: tbradsha <32492176+tbradsha@users.noreply.github.com>
@robelsust

Copy link
Copy Markdown

I strongly agree with @tbradsha's suggestion to return early rather than falling back to get_post().

There is an important lifecycle reason for this on after_delete_post:

  1. In wp_delete_post(), the database record is deleted and clean_post_cache() is executed before do_action( 'after_delete_post', ... ) fires.
  2. If third-party code invokes do_action( 'after_delete_post', $post_id ) using the legacy 1-argument signature, get_post( (int) $post_id ) is guaranteed to issue a wasted SQL query for a row that no longer exists in wp_posts.
  3. It will always return null, causing wp_random_content_flush_rewrite_rules_for_post() to fire a false-positive _doing_it_wrong() notice for a valid core hook invocation.

Returning early if $post is null or not a WP_Post avoids the extra query, avoids false notices on legacy action calls, and gracefully handles unexpected types.

@aaronjorbin

aaronjorbin commented Oct 20, 2026 •

Copy link
Copy Markdown
Member Author

There are four plugins that include references to do_action( 'after_delete_post': https://veloria.dev/search/e7fc52c2-2533-48e2-b59b-5921c46588fc one of which includes $post, one has the line commented out, one has the code but never runs it and the final is only in a comment as a part of a catalog of all core WP action hooks.

@tbradsha

Copy link
Copy Markdown

There are four plugins

I agree that the sample size there doesn't turn much up. That said, it's only representative of the most recent versions of plugins. Also, in the wild people install all sorts of plugins/themes that aren't in the WP.org repo, and also manually patch things and add code snippets all over the place. Without this PR, any such instances would fatal when updating WordPress, so thanks for taking this on. :^)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants