Skip to content

Commit 81abe8a

Browse files
committed
Load terms, meta and comments for batches of posts
Exporting a post ran separate queries for its terms, its meta, its comments and each comment's meta. Load all of them for the batch of posts that is already fetched together instead, which cuts the number of queries per batch of 100 posts from several hundred to about six. The output is unchanged: terms, meta and comments are ordered the same way as the per-post queries order them, `_edit_lock` and the `wxr_export_skip_postmeta` filter are still respected, and spam comments are still skipped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS
1 parent 759c8b2 commit 81abe8a

2 files changed

Lines changed: 201 additions & 3 deletions

File tree

‎features/export.feature‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1365,3 +1365,67 @@ Feature: Export content.
13651365
"""
13661366
<wp:meta_value><![CDATA[term_metavalue]]></wp:meta_value>
13671367
"""
1368+
1369+
Scenario: Export attaches terms, meta and comments to the right posts across batches
1370+
Given a WP install
1371+
And I run `wp site empty --yes`
1372+
And I run `wp post generate --count=150`
1373+
And I run `wp post create --post_title='Last post' --post_status=publish --tags_input='alpha,beta' --porcelain`
1374+
And save STDOUT as {LAST_POST_ID}
1375+
And I run `wp post meta add {LAST_POST_ID} my_meta_key my_meta_value`
1376+
And I run `wp post meta add {LAST_POST_ID} _edit_lock 123:1`
1377+
And I run `wp comment create --comment_post_ID={LAST_POST_ID} --comment_content='Approved comment' --comment_approved=1 --porcelain`
1378+
And save STDOUT as {COMMENT_ID}
1379+
And I run `wp comment meta add {COMMENT_ID} my_comment_meta_key my_comment_meta_value`
1380+
And I run `wp comment create --comment_post_ID={LAST_POST_ID} --comment_content='Spam comment' --comment_approved=spam`
1381+
And a check-export.php file:
1382+
"""
1383+
<?php
1384+
$xml = simplexml_load_file( $args[0] );
1385+
$found = 0;
1386+
foreach ( $xml->channel->item as $item ) {
1387+
$wp = $item->children( 'http://wordpress.org/export/1.2/' );
1388+
$tags = array();
1389+
foreach ( $item->category as $category ) {
1390+
if ( 'post_tag' === (string) $category['domain'] ) {
1391+
$tags[] = (string) $category['nicename'];
1392+
}
1393+
}
1394+
$meta = array();
1395+
foreach ( $wp->postmeta as $postmeta ) {
1396+
if ( in_array( (string) $postmeta->meta_key, array( '_pingme', '_encloseme' ), true ) ) {
1397+
continue;
1398+
}
1399+
$meta[] = (string) $postmeta->meta_key . '=' . (string) $postmeta->meta_value;
1400+
}
1401+
$comments = array();
1402+
foreach ( $wp->comment as $comment ) {
1403+
$comment_meta = array();
1404+
foreach ( $comment->commentmeta as $commentmeta ) {
1405+
$comment_meta[] = (string) $commentmeta->meta_key . '=' . (string) $commentmeta->meta_value;
1406+
}
1407+
$comments[] = (string) $comment->comment_content . ' [' . implode( ',', $comment_meta ) . ']';
1408+
}
1409+
if ( (string) $wp->post_id === '{LAST_POST_ID}' ) {
1410+
++$found;
1411+
echo 'tags: ' . implode( ',', $tags ) . "\n";
1412+
echo 'meta: ' . implode( ',', $meta ) . "\n";
1413+
echo 'comments: ' . implode( ',', $comments ) . "\n";
1414+
} elseif ( $tags || $meta || $comments ) {
1415+
echo 'unexpected data on post ' . $wp->post_id . "\n";
1416+
}
1417+
}
1418+
echo "found: $found\n";
1419+
"""
1420+
1421+
When I run `wp export --post_type=post`
1422+
Then save STDOUT 'Writing to file %s' as {EXPORT_FILE}
1423+
1424+
When I run `wp eval-file check-export.php {EXPORT_FILE}`
1425+
Then STDOUT should be:
1426+
"""
1427+
tags: alpha,beta
1428+
meta: my_meta_key=my_meta_value
1429+
comments: Approved comment [my_comment_meta_key=my_comment_meta_value]
1430+
found: 1
1431+
"""

‎src/WP_Export_Query.php‎

Lines changed: 137 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,20 @@ class WP_Export_Query {
3434

3535
public $missing_parents = false;
3636

37+
/**
38+
* Terms, meta and comments of the posts in the current batch, keyed by post ID.
39+
*
40+
* @var array<int, array{terms: array<\WP_Term>, meta: array<object>, comments: array<object>}>
41+
*/
42+
private $batch_data = [];
43+
44+
/**
45+
* Positions of the post IDs in $post_ids, to find the batch a post belongs to.
46+
*
47+
* @var array<int, int>|null
48+
*/
49+
private $post_id_positions;
50+
3751
public function __construct( $filters = [] ) {
3852
$this->filters = wp_parse_args( $filters, self::$defaults );
3953

@@ -156,9 +170,21 @@ public function exportify_post( $post ) {
156170
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
157171
$post->post_excerpt = apply_filters( 'the_excerpt_export', $post->post_excerpt );
158172
$post->is_sticky = is_sticky( $post->ID ) ? 1 : 0;
159-
$post->terms = self::get_terms_for_post( $post );
160-
$post->meta = self::get_meta_for_post( $post );
161-
$post->comments = $this->get_comments_for_post( $post );
173+
174+
if ( ! isset( $this->batch_data[ $post->ID ] ) ) {
175+
$this->load_batch_data( $post->ID );
176+
}
177+
178+
if ( isset( $this->batch_data[ $post->ID ] ) ) {
179+
$post->terms = $this->batch_data[ $post->ID ]['terms'];
180+
$post->meta = $this->batch_data[ $post->ID ]['meta'];
181+
$post->comments = $this->batch_data[ $post->ID ]['comments'];
182+
unset( $this->batch_data[ $post->ID ] );
183+
} else {
184+
$post->terms = self::get_terms_for_post( $post );
185+
$post->meta = self::get_meta_for_post( $post );
186+
$post->comments = $this->get_comments_for_post( $post );
187+
}
162188
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Revert back to original.
163189
$GLOBALS['post'] = $previous_global_post;
164190
return $post;
@@ -413,6 +439,114 @@ private function process_orphaned_terms( $terms ) {
413439
return $terms;
414440
}
415441

442+
/**
443+
* Load the terms, meta and comments of the batch of posts starting with the given one.
444+
*
445+
* Querying them for a whole batch at once avoids several queries per exported post.
446+
* The data is the same as what get_terms_for_post(), get_meta_for_post() and
447+
* get_comments_for_post() return for each post.
448+
*
449+
* @param int $post_id ID of the first post of the batch.
450+
*/
451+
private function load_batch_data( $post_id ) {
452+
global $wpdb;
453+
454+
if ( null === $this->post_id_positions ) {
455+
$this->post_id_positions = array_flip( array_map( 'intval', $this->post_ids ) );
456+
}
457+
458+
$this->batch_data = [];
459+
if ( ! isset( $this->post_id_positions[ $post_id ] ) ) {
460+
return;
461+
}
462+
463+
$post_ids = array_map( 'intval', array_slice( $this->post_ids, $this->post_id_positions[ $post_id ], self::QUERY_CHUNK ) );
464+
$in_ids = implode( ',', $post_ids );
465+
466+
$terms_by_post = array_fill_keys( $post_ids, [] );
467+
$meta_by_post = array_fill_keys( $post_ids, [] );
468+
$comments_by_post = array_fill_keys( $post_ids, [] );
469+
470+
// Terms, queried per post type as the taxonomies depend on it.
471+
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- integers only
472+
$post_types = $wpdb->get_results( "SELECT ID, post_type FROM $wpdb->posts WHERE ID IN ($in_ids)" );
473+
$ids_by_type = [];
474+
foreach ( $post_types as $row ) {
475+
$ids_by_type[ $row->post_type ][] = (int) $row->ID;
476+
}
477+
foreach ( $ids_by_type as $post_type => $ids ) {
478+
$taxonomies = get_object_taxonomies( $post_type );
479+
if ( empty( $taxonomies ) ) {
480+
continue;
481+
}
482+
$terms = wp_get_object_terms( $ids, $taxonomies, [ 'fields' => 'all_with_object_id' ] );
483+
if ( is_wp_error( $terms ) ) {
484+
continue;
485+
}
486+
foreach ( $terms as $term ) {
487+
if ( ! $term instanceof \WP_Term ) {
488+
continue;
489+
}
490+
// Set by wp_get_object_terms() for 'all_with_object_id'.
491+
$object_id = (int) $term->object_id; // @phpstan-ignore property.notFound
492+
if ( isset( $terms_by_post[ $object_id ] ) ) {
493+
$terms_by_post[ $object_id ][] = $term;
494+
}
495+
}
496+
}
497+
498+
// Terms are ordered by name. Order terms with the same name, e.g. a category and a tag,
499+
// by their term_taxonomy_id like the query for a single post returns them.
500+
foreach ( $terms_by_post as &$terms ) {
501+
usort(
502+
$terms,
503+
static function ( $a, $b ) {
504+
return [ $a->name, $a->term_taxonomy_id ] <=> [ $b->name, $b->term_taxonomy_id ];
505+
}
506+
);
507+
}
508+
unset( $terms );
509+
510+
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- integers only
511+
$meta_from_db = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta WHERE post_id IN ($in_ids) ORDER BY post_id, meta_id" );
512+
foreach ( $meta_from_db as $meta ) {
513+
if ( '_edit_lock' === $meta->meta_key ) {
514+
continue;
515+
}
516+
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
517+
if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) ) {
518+
continue;
519+
}
520+
$meta_by_post[ (int) $meta->post_id ][] = $meta;
521+
}
522+
523+
if ( ! isset( $this->filters['skip_comments'] ) ) {
524+
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- integers only
525+
$comments = $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_post_ID IN ($in_ids) AND comment_approved <> 'spam' ORDER BY comment_post_ID, comment_ID" );
526+
if ( ! empty( $comments ) ) {
527+
$comment_meta = [];
528+
$comment_ids = implode( ',', array_map( 'intval', wp_list_pluck( $comments, 'comment_ID' ) ) );
529+
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- integers only
530+
foreach ( $wpdb->get_results( "SELECT * FROM $wpdb->commentmeta WHERE comment_id IN ($comment_ids) ORDER BY comment_id, meta_id" ) as $meta ) {
531+
$comment_meta[ (int) $meta->comment_id ][] = $meta;
532+
}
533+
534+
foreach ( $comments as $comment ) {
535+
$comment->meta = isset( $comment_meta[ (int) $comment->comment_ID ] ) ? $comment_meta[ (int) $comment->comment_ID ] : [];
536+
$comments_by_post[ (int) $comment->comment_post_ID ][] = $comment;
537+
}
538+
}
539+
}
540+
541+
foreach ( $post_ids as $id ) {
542+
$this->batch_data[ $id ] = [
543+
'terms' => $terms_by_post[ $id ],
544+
'meta' => $meta_by_post[ $id ],
545+
'comments' => $comments_by_post[ $id ],
546+
];
547+
}
548+
}
549+
416550
private static function get_terms_for_post( $post ) {
417551
$taxonomies = get_object_taxonomies( $post->post_type );
418552
if ( empty( $taxonomies ) ) {

0 commit comments

Comments
 (0)