• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Yoast / wordpress-seo / b01973fe2ec02214545b7597987dd7199ae93ce7

04 Aug 2026 12:31PM UTC coverage: 55.45% (-0.3%) from 55.778%
b01973fe2ec02214545b7597987dd7199ae93ce7

Pull #23538

github

web-flow
Merge a4ea615a3 into 0de900db2
Pull Request #23538: fix(bulk-editor): resolve post type default template when SEO title/description is empty

9798 of 17512 branches covered (55.95%)

Branch coverage included in aggregate %.

47 of 60 new or added lines in 3 files covered. (78.33%)

1 existing line in 1 file now uncovered.

39310 of 71051 relevant lines covered (55.33%)

42358.28 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.33
/src/bulk-editor/infrastructure/posts/indexable-posts-collector.php
1
<?php
2

3
// phpcs:disable Yoast.NamingConventions.NamespaceName.TooLong -- Needed in the folder structure.
4
namespace Yoast\WP\SEO\Bulk_Editor\Infrastructure\Posts;
5

6
use Yoast\WP\Lib\ORM;
7
use Yoast\WP\SEO\Bulk_Editor\Application\Posts\Posts_Collector_Interface;
8
use Yoast\WP\SEO\Bulk_Editor\Domain\Posts\Post;
9
use Yoast\WP\SEO\Bulk_Editor\Domain\Posts\Posts_List;
10
use Yoast\WP\SEO\Bulk_Editor\Domain\Posts\Posts_Page;
11
use Yoast\WP\SEO\Bulk_Editor\Domain\Posts\Posts_Query;
12
use Yoast\WP\SEO\Models\Indexable;
13
use Yoast\WP\SEO\Repositories\Indexable_Repository;
14

15
/**
16
 * Collects bulk editor posts by reading from the indexable table.
17
 *
18
 * This is the default used when indexables are active.
19
 */
20
class Indexable_Posts_Collector implements Posts_Collector_Interface {
21

22
        use Post_Title_Trait;
23
        use Searchable_Fields_Trait;
24

25
        /**
26
         * Maps each "needs improvement" field key to its indexable column.
27
         *
28
         * @var array<string, string>
29
         */
30
        private const FIELD_COLUMNS = [
31
                'seo_title'          => 'title',
32
                'meta_description'   => 'description',
33
                'social_title'       => 'open_graph_title',
34
                'social_description' => 'open_graph_description',
35
        ];
36

37
        /**
38
         * Maps the fields with a persisted per-field score to their indexable score column.
39
         *
40
         * The social fields have no assessors, so they match on emptiness only.
41
         *
42
         * @var array<string, string>
43
         */
44
        private const FIELD_SCORE_COLUMNS = [
45
                'seo_title'        => 'seo_title_score',
46
                'meta_description' => 'meta_description_score',
47
        ];
48

49
        /**
50
         * The indexable repository.
51
         *
52
         * @var Indexable_Repository
53
         */
54
        private $indexable_repository;
55

56
        /**
57
         * The resolver for the per-post edit permission.
58
         *
59
         * @var Post_Editability_Resolver
60
         */
61
        private $post_editability_resolver;
62

63
        /**
64
         * The resolver for the post type's default SEO title / meta description template.
65
         *
66
         * @var Default_Template_Resolver
67
         */
68
        private $default_template_resolver;
69

70
        /**
71
         * The constructor.
72
         *
73
         * @param Indexable_Repository      $indexable_repository      The indexable repository.
74
         * @param Post_Editability_Resolver $post_editability_resolver The resolver for the per-post edit permission.
75
         * @param Default_Template_Resolver $default_template_resolver The resolver for the default SEO title / meta description template.
76
         */
77
        public function __construct(
×
78
                Indexable_Repository $indexable_repository,
79
                Post_Editability_Resolver $post_editability_resolver,
80
                Default_Template_Resolver $default_template_resolver
81
        ) {
82
                $this->indexable_repository      = $indexable_repository;
×
83
                $this->post_editability_resolver = $post_editability_resolver;
×
NEW
84
                $this->default_template_resolver = $default_template_resolver;
×
85
        }
86

87
        /**
88
         * Collects a page of posts for the given query.
89
         *
90
         * A single page is fetched and counted through the database; the per-post edit permission is then
91
         * resolved for that page so posts the user cannot edit are returned locked and without their SEO data.
92
         *
93
         * @param Posts_Query $query The query describing the page to collect.
94
         *
95
         * @return Posts_Page The collected posts together with the totals for pagination.
96
         */
97
        public function get_posts( Posts_Query $query ): Posts_Page {
24✔
98
                $indexables = $this->build_query( $query )
24✔
99
                        ->order_by_desc( 'object_id' )
24✔
100
                        ->limit( $query->get_per_page() )
24✔
101
                        ->offset( $query->get_offset() )
24✔
102
                        ->find_many();
24✔
103

104
                // Deduplicate on the post, keeping the query order.
105
                $indexables_by_id = [];
24✔
106
                foreach ( $indexables as $indexable ) {
24✔
107
                        $indexables_by_id[ (int) $indexable->object_id ] = $indexable;
14✔
108
                }
109

110
                $total = $this->resolve_total( $query, \count( $indexables ), \count( $indexables_by_id ) );
24✔
111

112
                $editability = $this->post_editability_resolver->resolve( \array_keys( $indexables_by_id ) );
24✔
113

114
                $posts_list = new Posts_List();
24✔
115
                foreach ( $indexables_by_id as $object_id => $indexable ) {
24✔
116
                        $posts_list->add( $this->build_post( $indexable, ( $editability[ $object_id ] ?? false ), $query->are_scores_enabled() ) );
14✔
117
                }
118

119
                return new Posts_Page( $posts_list, $total, $query->get_page(), $query->get_per_page() );
24✔
120
        }
121

122
        /**
123
         * Resolves the total number of matching posts.
124
         *
125
         * A partially-filled page means the result set ended within it, so the total is known without a
126
         * second query: the offset plus the distinct posts on this page. Whether the page ended is judged
127
         * on the number of rows fetched, before duplicates are removed, since that is what reveals the
128
         * database had no more rows. A full or empty page does not reveal the total, so it falls back to a
129
         * count query. Non-editable posts are shown locked rather than removed, so they still count.
130
         *
131
         * @param Posts_Query $query    The query that produced the page.
132
         * @param int         $fetched  The number of rows the page returned, before duplicates are removed.
133
         * @param int         $distinct The number of distinct posts on the page, after duplicates are removed.
134
         *
135
         * @return int The total number of matching posts.
136
         */
137
        private function resolve_total( Posts_Query $query, int $fetched, int $distinct ): int {
24✔
138
                if ( $fetched > 0 && $fetched < $query->get_per_page() ) {
24✔
139
                        return ( $query->get_offset() + $distinct );
12✔
140
                }
141

142
                return (int) $this->build_query( $query )->count();
12✔
143
        }
144

145
        /**
146
         * Builds the filtered indexable query for the given query, without ordering or paging.
147
         *
148
         * Built fresh for each use so the same filters back both the total count and the page of rows.
149
         *
150
         * @param Posts_Query $query The query describing the filters to apply.
151
         *
152
         * @return ORM The filtered query.
153
         */
154
        private function build_query( Posts_Query $query ): ORM {
24✔
155
                $builder = $this->indexable_repository->query()
24✔
156
                        ->where( 'object_type', 'post' )
24✔
157
                        ->where( 'object_sub_type', $query->get_content_type() )
24✔
158
                        ->where_in( 'post_status', $query->get_statuses() )
24✔
159
                        // Password-protected posts (is_protected) are not shown in bulk editing.
24✔
160
                        ->where( 'is_protected', 0 );
24✔
161

162
                if ( $query->has_author_filter() ) {
24✔
163
                        $builder->where( 'author_id', $query->get_author_id() );
×
164
                }
165

166
                if ( $query->has_include() ) {
24✔
167
                        $builder->where_in( 'object_id', $query->get_include_ids() );
2✔
168
                }
169

170
                if ( $query->has_search() ) {
24✔
171
                        $this->apply_search( $builder, $query->get_search() );
2✔
172
                }
173

174
                if ( $query->get_needs_improvement() !== [] ) {
24✔
175
                        $this->apply_needs_improvement( $builder, $query->get_needs_improvement(), $query->are_scores_enabled() );
6✔
176
                }
177

178
                return $builder;
24✔
179
        }
180

181
        /**
182
         * Adds the "needs improvement" clause to the query.
183
         *
184
         * A field needs improvement when its indexable column is NULL or an empty string, or — for fields
185
         * with a persisted per-field score and while scoring is enabled — when that score falls in the bad/ok
186
         * range. The selected fields are OR-ed inside a single group so they broaden the result without
187
         * interfering with the other filters, and unknown field keys are ignored.
188
         *
189
         * @param ORM           $builder        The query to add the clause to.
190
         * @param array<string> $fields         The fields that need improvement.
191
         * @param bool          $scores_enabled Whether the per-field scores may back the filter.
192
         *
193
         * @return void
194
         */
195
        private function apply_needs_improvement( ORM $builder, array $fields, bool $scores_enabled ): void {
6✔
196
                $clauses = [];
6✔
197
                $values  = [];
6✔
198
                foreach ( $fields as $field ) {
6✔
199
                        if ( ! isset( self::FIELD_COLUMNS[ $field ] ) ) {
6✔
200
                                continue;
×
201
                        }
202

203
                        $column   = self::FIELD_COLUMNS[ $field ];
6✔
204
                        $clause   = $column . ' IS NULL OR ' . $column . ' = %s';
6✔
205
                        $values[] = '';
6✔
206

207
                        if ( $scores_enabled && isset( self::FIELD_SCORE_COLUMNS[ $field ] ) ) {
6✔
208
                                $clause  .= ' OR ' . self::FIELD_SCORE_COLUMNS[ $field ] . ' BETWEEN %d AND %d';
2✔
209
                                $values[] = self::NEEDS_IMPROVEMENT_MIN_SCORE;
2✔
210
                                $values[] = self::NEEDS_IMPROVEMENT_MAX_SCORE;
2✔
211
                        }
212

213
                        $clauses[] = '( ' . $clause . ' )';
6✔
214
                }
215

216
                if ( $clauses === [] ) {
6✔
217
                        return;
×
218
                }
219

220
                // The column names come from the internal maps, never from input; only the empty string and score bounds are bound.
221
                $builder->where_raw(
6✔
222
                        '( ' . \implode( ' OR ', $clauses ) . ' )',
6✔
223
                        $values,
6✔
224
                );
6✔
225
        }
226

227
        /**
228
         * Adds the catch-all search clause to the query.
229
         *
230
         * The post title lives in the posts table, so it is matched through a subquery while the remaining
231
         * fields are matched directly on the indexable. All clauses are OR-ed inside a single group so they
232
         * do not interfere with the other filters.
233
         *
234
         * @param ORM    $builder The query to add the search clause to.
235
         * @param string $search  The search term.
236
         *
237
         * @return void
238
         */
239
        private function apply_search( ORM $builder, string $search ): void {
2✔
240
                global $wpdb;
2✔
241

242
                $like = '%' . $wpdb->esc_like( $search ) . '%';
2✔
243

244
                // The post title lives in the posts table, so match it through a subquery; the rest are indexable columns.
245
                $clauses = [ 'object_id IN ( SELECT ID FROM ' . $wpdb->posts . ' WHERE post_title LIKE %s )' ];
2✔
246
                foreach ( \array_keys( $this->searchable_fields() ) as $column ) {
2✔
247
                        $clauses[] = $column . ' LIKE %s';
2✔
248
                }
249

250
                // The ORM binds each %s through $wpdb->prepare; one bound value per clause.
251
                $builder->where_raw(
2✔
252
                        '( ' . \implode( ' OR ', $clauses ) . ' )',
2✔
253
                        \array_fill( 0, \count( $clauses ), $like ),
2✔
254
                );
2✔
255
        }
256

257
        /**
258
         * Builds a post from an indexable.
259
         *
260
         * The SEO data and edit link of a post the current user cannot edit are withheld, so the post is
261
         * shown in the list but stays locked and does not expose its metadata.
262
         *
263
         * @param Indexable $indexable      The indexable.
264
         * @param bool      $editable       Whether the current user may edit the post.
265
         * @param bool      $scores_enabled Whether the per-field scores may back the needs-improvement verdict.
266
         *
267
         * @return Post The post.
268
         */
269
        private function build_post( Indexable $indexable, bool $editable, bool $scores_enabled ): Post {
14✔
270
                $object_id = (int) $indexable->object_id;
14✔
271
                $title     = $this->get_normalized_title( $object_id );
14✔
272

273
                if ( ! $editable ) {
14✔
274
                        return new Post( $object_id, $title, (string) $indexable->post_status, '', '', '', '', '', '', false );
2✔
275
                }
276

277
                $post_type       = (string) $indexable->object_sub_type;
12✔
278
                $resolved_values = [
12✔
279
                        'seo_title'          => $this->default_template_resolver->resolve_seo_title( $object_id, $post_type, (string) $indexable->title ),
12✔
280
                        'meta_description'   => $this->default_template_resolver->resolve_meta_description( $object_id, $post_type, (string) $indexable->description ),
12✔
281
                        'social_title'       => $this->default_template_resolver->resolve_social_title( $object_id, $post_type, (string) $indexable->open_graph_title ),
12✔
282
                        'social_description' => $this->default_template_resolver->resolve_social_description( $object_id, $post_type, (string) $indexable->open_graph_description ),
12✔
283
                ];
12✔
284

285
                return new Post(
12✔
286
                        $object_id,
12✔
287
                        $title,
12✔
288
                        (string) $indexable->post_status,
12✔
289
                        (string) \get_edit_post_link( $object_id, 'raw' ),
12✔
290
                        (string) $indexable->primary_focus_keyword,
12✔
291
                        $resolved_values['seo_title'],
12✔
292
                        $resolved_values['meta_description'],
12✔
293
                        $resolved_values['social_title'],
12✔
294
                        $resolved_values['social_description'],
12✔
295
                        true,
12✔
296
                        $this->build_needs_improvement( $indexable, $scores_enabled, $resolved_values ),
12✔
297
                );
12✔
298
        }
299

300
        /**
301
         * Builds the per-field needs-improvement verdict for a post, keyed by field param.
302
         *
303
         * A field needs improvement when its value is empty, or when its score falls in the bad/ok range.
304
         * All four display values are passed in already-resolved so that a post whose stored value is empty
305
         * but whose post type has a configured default template is not incorrectly flagged.
306
         *
307
         * @param Indexable             $indexable       The indexable.
308
         * @param bool                  $scores_enabled  Whether the per-field scores may back the verdict.
309
         * @param array<string, string> $resolved_values The resolved display values, keyed by field param.
310
         *
311
         * @return array<string, bool> Whether each field needs improvement, keyed by field param.
312
         */
313
        private function build_needs_improvement( Indexable $indexable, bool $scores_enabled, array $resolved_values ): array {
12✔
314
                $needs_improvement = [];
12✔
315
                foreach ( self::FIELD_COLUMNS as $field => $column ) {
12✔
316
                        $value    = ( $resolved_values[ $field ] ?? (string) $indexable->{$column} );
12✔
317
                        $is_empty = ( $value === '' );
12✔
318

319
                        $is_bad_score = false;
12✔
320
                        if ( $scores_enabled && isset( self::FIELD_SCORE_COLUMNS[ $field ] ) ) {
12✔
321
                                $score        = (int) $indexable->{self::FIELD_SCORE_COLUMNS[ $field ]};
12✔
322
                                $is_bad_score = ( $score >= self::NEEDS_IMPROVEMENT_MIN_SCORE && $score <= self::NEEDS_IMPROVEMENT_MAX_SCORE );
12✔
323
                        }
324

325
                        $needs_improvement[ $field ] = ( $is_empty || $is_bad_score );
12✔
326
                }
327

328
                return $needs_improvement;
12✔
329
        }
330
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc