Skip to content

Commit 7fc744d

Browse files
Copilotswissspidy
andcommitted
Query term relationships directly from database
Instead of relying on wp_get_object_terms() which may have cache issues with posts retrieved directly from the database, query the term_relationships table directly and then fetch full term objects. This ensures term relationships are always retrieved correctly regardless of cache state. Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
1 parent 948aca3 commit 7fc744d

1 file changed

Lines changed: 24 additions & 4 deletions

File tree

src/WP_Export_Query.php

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,6 @@ public function nav_menu_terms() {
137137
}
138138

139139
public function exportify_post( $post ) {
140-
// Ensure we have a proper WP_Post object for term retrieval.
141-
$post = get_post( $post );
142140
$GLOBALS['wp_query']->in_the_loop = true;
143141
$previous_global_post = Utils\get_flag_value( $GLOBALS, 'post' );
144142
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Temporary override.
@@ -404,14 +402,36 @@ private function process_orphaned_terms( $terms ) {
404402
}
405403

406404
private static function get_terms_for_post( $post ) {
405+
global $wpdb;
407406
$taxonomies = get_object_taxonomies( $post->post_type );
408407
if ( empty( $taxonomies ) ) {
409408
return [];
410409
}
411-
$terms = wp_get_object_terms( $post->ID, $taxonomies );
412-
if ( is_wp_error( $terms ) ) {
410+
411+
// Query database directly for term relationships to avoid cache issues.
412+
$term_ids = $wpdb->get_col(
413+
$wpdb->prepare(
414+
"SELECT tt.term_id
415+
FROM {$wpdb->term_relationships} AS tr
416+
INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
417+
WHERE tr.object_id = %d",
418+
$post->ID
419+
)
420+
);
421+
422+
if ( empty( $term_ids ) ) {
413423
return [];
414424
}
425+
426+
// Now get the full term objects.
427+
$terms = [];
428+
foreach ( $term_ids as $term_id ) {
429+
$term = get_term( $term_id );
430+
if ( $term && ! is_wp_error( $term ) && in_array( $term->taxonomy, $taxonomies, true ) ) {
431+
$terms[] = $term;
432+
}
433+
}
434+
415435
return $terms;
416436
}
417437

0 commit comments

Comments
 (0)