Im trying to show taxonomy names along with their counts for a donut-chart. This is what im doing;
<ul class="pie-chart__legend" id="donut1">
<?php
$wcatTerms1 = get_terms('incident_type', array('hide_empty' => 0, 'parent' =>0));
foreach($wcatTerms1 as $wcatTerm1)
{
$args1 = array(
'posts_per_page' => -1,
'post_type' => 'incident',
'post_author' => $current_user->ID,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'incident_type',
'field' => 'term_id',
'terms' => $wcatTerm1,
'include_children' => false
)
));
$count1 = 0;
$query1 = new WP_Query($args1);
while ( $query1->have_posts() )
{
$count1++;
}
?>
<li><em><?php echo $wcatTerm1->name; ?></em><span><?php echo $count1; ?></span></li>
<?php
}
?>
But this is running infinite and eventually timing out. I tried several fixies involving the_posts() but not working.
Kindly let me know what i am doing wrong.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I have figured out. I was missing $query1->the_post(); in the while loop and wp_reset_postdata(); after the loop ends.
Final working code:
<ul class="pie-chart__legend" id="donut1">
<?php
$wcatTerms1 = get_terms('incident_type', array('hide_empty' => 0, 'parent' =>0));
foreach($wcatTerms1 as $wcatTerm1)
{
$args1 = array(
'posts_per_page' => -1,
'post_type' => 'incident',
'post_author' => $current_user->ID,
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'incident_type',
'field' => 'term_id',
'terms' => $wcatTerm1,
'include_children' => false
)
));
$count1 = 0;
$query1 = new WP_Query($args1);
while ( $query1->have_posts() )
{
$query1->the_post();
$count1++;
}
?>
<li><em><?php echo $wcatTerm1->name; ?></em><span><?php echo $count1; ?></span></li>
<?php
wp_reset_postdata();
}
?>
</ul>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0