Well based on this topic I figured it was best to open a new one since I have a couple more questions besides the one I posted there.
I want to have a loop that shows a post of each custom taxonomy (themes). But also shows a maximum of 2 posts per CPT.
Themes are global to every CPT we have on our website.
::
I created a Custom taxonomy called ‘Themes’
This is out I set it up:
Outer loop: https://i.imgur.com/zcWZo60.png
Inner loop: https://i.imgur.com/8kILCnX.png and https://i.imgur.com/3UhkmeT.png
But it didn’t work with {post_terms_customthemes} so I put {term_name} but not sure if that is working. because it shows repeated posts.
Also not sure how I could limit to show a max of 2 posts per CPT.
This will be showed in a SLIDER. The slider itself is a Brickxextras element.
Well with a bit LOT of help of Claude3.5 I was able to get a query that fit my needs.
Could you let me know if this is the proper way to do this? I may need more in the future for other loops so this would be really appreciated.
I’m also concerned about performance issues that a solution like this could cause.
Code here
// Define the post types we want to query
$post_types = array('sfwd-courses', 'podcast', 'document', 'video');
// ADJUSTABLE PARAMETERS
$total_posts_to_show = 10; // Total number of posts to display
$max_posts_per_cpt = 3; // Maximum number of posts per Custom Post Type
$posts_per_theme = 1; // Number of posts to show per theme (Themes)
// Initialize an array to store our query results
$query_results = array();
// Initialize a counter for each post type
$post_type_counts = array_fill_keys($post_types, 0);
// Get all terms from the 'themes' taxonomy
$terms = get_terms(array(
'taxonomy' => 'themes',
'hide_empty' => true,
));
// Loop through each term
foreach ($terms as $term) {
$args = array(
'post_type' => $post_types,
'posts_per_page' => $posts_per_theme,
'tax_query' => array(
array(
'taxonomy' => 'themes',
'field' => 'term_id',
'terms' => $term->term_id,
),
),
'meta_query' => array(
array(
'key' => 'cpt_most_accessed',
'value' => '1',
'compare' => '=',
),
),
);
$query = new WP_Query($args);
while ($query->have_posts()) {
$query->the_post();
$current_post_type = get_post_type();
if ($post_type_counts[$current_post_type] < $max_posts_per_cpt) {
$query_results[] = get_the_ID();
$post_type_counts[$current_post_type]++;
if (count($query_results) >= $total_posts_to_show) {
break 2; // Break both while and foreach loops
}
}
}
wp_reset_postdata();
}
// Return the query parameters as a PHP array
return array(
'post_type' => $post_types,
'post__in' => $query_results,
'posts_per_page' => count($query_results),
'orderby' => 'post__in',
);
1 Like