Skip to content

Commit 0f37ec4

Browse files
authored
feat: add helper function to get all sponsored terms (#263)
* feat: add helper function to get all sponsored terms * fix: array_map arg order
1 parent 0b7ab2b commit 0f37ec4

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

includes/theme-helpers.php

+59
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,65 @@ function get_sponsor_posts_for_terms( $terms ) {
354354
return $sponsor_posts->posts;
355355
}
356356

357+
/**
358+
* Get all sponsored terms.
359+
*
360+
* @return array|boolean An associative array keyed by taxonomy name with an array of sponsored term IDs for each, or false if no sponsored terms.
361+
*/
362+
function get_all_sponsored_terms() {
363+
$taxonomies = \get_object_taxonomies( Core::NEWSPACK_SPONSORS_CPT );
364+
if ( empty( $taxonomies ) ) {
365+
return false;
366+
}
367+
368+
$tax_query_args = array_map(
369+
function( $taxonomy ) {
370+
return [
371+
'taxonomy' => $taxonomy,
372+
'operator' => 'EXISTS',
373+
];
374+
},
375+
$taxonomies
376+
);
377+
378+
$tax_query_args['relation'] = 'OR';
379+
$sponsors_with_terms = new \WP_Query(
380+
[
381+
'is_sponsors' => 1,
382+
'fields' => 'ids',
383+
'post_type' => Core::NEWSPACK_SPONSORS_CPT,
384+
'posts_per_page' => 100,
385+
'post_status' => 'publish',
386+
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
387+
'tax_query' => $tax_query_args,
388+
]
389+
);
390+
391+
if ( empty( $sponsors_with_terms->posts ) ) {
392+
return false;
393+
}
394+
395+
$sponsored_terms = \get_terms(
396+
[
397+
'taxonomy' => $taxonomies,
398+
'object_ids' => $sponsors_with_terms->posts,
399+
]
400+
);
401+
402+
return array_reduce(
403+
$sponsored_terms,
404+
function( $acc, $term ) {
405+
if ( ! isset( $acc[ $term->taxonomy ] ) ) {
406+
$acc[ $term->taxonomy ] = [];
407+
}
408+
409+
$acc[ $term->taxonomy ][] = $term->term_id;
410+
return $acc;
411+
},
412+
[]
413+
);
414+
}
415+
357416
/**
358417
* Formats a post object into a sponsor object, for ease of theme developer use.
359418
*

0 commit comments

Comments
 (0)