From ea62e9535d24a49fdc1e5304811ff50c378de97d Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 11 Aug 2026 16:18:57 -0500 Subject: [PATCH] fix: reuse CHRNX term caches --- inc/queries.php | 8 ++++-- tests/php/BlockRenderingTest.php | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/inc/queries.php b/inc/queries.php index 7d5a468..d35e524 100644 --- a/inc/queries.php +++ b/inc/queries.php @@ -153,8 +153,12 @@ function chrnx_get_eligible_editorial_post_ids( $extra_args = array() ) { * @return string Topic slug or empty string. */ function chrnx_get_post_topic_slug( $post_id ) { - $terms = wp_get_object_terms( $post_id, 'chrnx_topic', array( 'fields' => 'slugs' ) ); - return ! is_wp_error( $terms ) && ! empty( $terms ) ? (string) reset( $terms ) : ''; + $terms = get_the_terms( $post_id, 'chrnx_topic' ); + if ( is_wp_error( $terms ) || empty( $terms ) ) { + return ''; + } + $term = reset( $terms ); + return $term instanceof WP_Term ? (string) $term->slug : ''; } /** diff --git a/tests/php/BlockRenderingTest.php b/tests/php/BlockRenderingTest.php index 2eeb971..10fae70 100644 --- a/tests/php/BlockRenderingTest.php +++ b/tests/php/BlockRenderingTest.php @@ -172,6 +172,48 @@ class BlockRenderingTest extends WP_UnitTestCase { $this->assertStringNotContainsString( 'placeholder', strtolower( $output ) ); } + /** Primed editorial cards reuse relationship caches instead of querying once per fallback. */ + public function test_maximum_featured_render_has_no_term_relationship_n_plus_one() { + for ( $index = 1; $index <= 12; ++$index ) { + $post_id = self::factory()->post->create( + array( + 'post_title' => 'Cached card ' . $index, + 'post_date' => sprintf( '2026-05-%02d 10:00:00', $index ), + ) + ); + wp_set_object_terms( $post_id, 'research', 'chrnx_topic' ); + } + + $ids = chrnx_get_featured_story_ids( 12 ); + $this->assertCount( 12, $ids ); + _prime_post_caches( $ids, true, true ); + + $term_queries = array(); + $capture = static function ( $sql ) use ( &$term_queries ) { + if ( false !== stripos( $sql, 'term_relationships' ) ) { + $term_queries[] = $sql; + } + return $sql; + }; + add_filter( 'query', $capture ); + try { + $output = render_block( + array( + 'blockName' => 'chrnx/featured-stories', + 'attrs' => array( 'limit' => 12 ), + 'innerBlocks' => array(), + 'innerHTML' => '', + 'innerContent' => array(), + ) + ); + } finally { + remove_filter( 'query', $capture ); + } + + $this->assertSame( 12, substr_count( $output, 'assertSame( array(), $term_queries, 'Warm rendering must not issue per-card relationship queries.' ); + } + /** Stored title markup is displayed literally and cannot inject executable elements. */ public function test_editorial_cards_escape_stored_title_markup() { $title = '';