WP_Query in a custom block not working
-
Hi everyone,
I am currently building a custom block that will be used to display lists of posts in a very specific way. What I need is for posts to be grouped by sub-categories, with the name of each subcategory being displayed as header. Basically like this :
Category 1
Subcategory 1A
- Post 1
- Post 2
Subcategory 1B
- Post 3
- Post 4
This is how I want posts to be diplayed in category archive pages. I couldn’t find a way to customize the query loop block to fit my need – as it requires running a wp_query loop within a get_terms loop that fetches and display all the subcategories available – so I went for a custom block.
Here is the code I put together for the render :
function custom_post_list_render($attr) {
$queried_object = get_queried_object();
$cat_active = $queried_object->term_id;
$subcategories = get_terms(array(
'taxonomy' => $attr['taxonomy'],
'parent' => $cat_active,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => FALSE,
));
$output = '<div ' . get_block_wrapper_attributes() . '>';
foreach ($subcategories as $subcategory) {
$subcat_name = $subcategory-> name;
$subcat_id = $subcategory -> term_id;
$output .= '<div id="subcategory-' . $subcat_id . '" class= "subcategory-post-list">';
$output .= '<div class="subcategory-title">' . $subcat_name . '</div><ul class="post-list">';
$args = array(
'post_type' => $attr['post_type'],
'cat' => $subcat_id,
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) :
$query->the_post();
$output .= '<li>' . the_title() . '<i class="bi bi-chevron-right"></i></li>';
endwhile;
endif;
$output .= '</div>';
wp_reset_postdata();
}
$output .= '</div>';
return $output;
}I included the block in my category archive page template to test it and while it does return the subcategory names as expected, it does not list the posts. There seem to be an issue with my use of WP_Query.
Any idea on what is wrong here ?
Thank in advance for your responses !
- You must be logged in to reply to this topic.