diff --git a/src/wp-includes/query.php b/src/wp-includes/query.php index 8256ef22859a5..f3aac6f10644c 100644 --- a/src/wp-includes/query.php +++ b/src/wp-includes/query.php @@ -1918,15 +1918,21 @@ function wp_random_content_flush_rewrite_rules_for_post( $post_id, $post = null, } foreach ( $posts as $page ) { + /* + * Check the post type and parent first. Reading the random base can switch the + * locale, which is too costly to do for every revision, autosave or menu item. + */ if ( - $wp_rewrite->get_random_base() === $page->post_name - && ( - ( 'page' === $page->post_type && 0 === (int) $page->post_parent ) - || ( 'post' === $page->post_type && $wp_rewrite->post_permalinks_share_random_base() ) - ) + ( 'page' === $page->post_type && 0 === (int) $page->post_parent ) + || 'post' === $page->post_type ) { - flush_rewrite_rules( false ); - return; + if ( + $wp_rewrite->get_random_base() === $page->post_name + && ( 'page' === $page->post_type || $wp_rewrite->post_permalinks_share_random_base() ) + ) { + flush_rewrite_rules( false ); + return; + } } } } diff --git a/tests/phpunit/tests/query/randomContentRedirect.php b/tests/phpunit/tests/query/randomContentRedirect.php index 55e0cd025bc3b..8f9b32880b66d 100644 --- a/tests/phpunit/tests/query/randomContentRedirect.php +++ b/tests/phpunit/tests/query/randomContentRedirect.php @@ -2014,6 +2014,51 @@ public function test_saving_unrelated_pages_does_not_flush_rewrite_rules(): void $this->assertSame( 0, $flushes->get_call_count(), 'Only pages and posts at the random base should flush the rewrite rules.' ); } + /** + * Ensure saving a post that can never be at the random base does not read the random base, + * since reading it can switch the locale. + */ + public function test_saving_posts_that_cannot_be_at_the_random_base_does_not_read_the_random_base(): void { + $reads = new MockAction(); + add_filter( + 'gettext_with_context_default', + static function ( $translation, $text, $context ) use ( $reads ) { + if ( 'random content permalink base' === $context ) { + $reads->filter( $translation ); + } + return $translation; + }, + 10, + 3 + ); + + $parent = $this->create_post( array( 'post_type' => 'page' ) ); + $reads->reset(); + + $this->create_post( + array( + 'post_type' => 'page', + 'post_name' => 'random', + 'post_parent' => $parent, + ) + ); + $this->create_post( + array( + 'post_type' => 'attachment', + 'post_name' => 'random', + ) + ); + $this->create_post( + array( + 'post_type' => 'revision', + 'post_name' => 'random', + 'post_parent' => $parent, + ) + ); + + $this->assertSame( 0, $reads->get_call_count(), 'Only top-level pages and posts should read the random base.' ); + } + /** * @dataProvider data_invalid_arguments *