I am having an array of Objects returned by WP_Query->posts
array
0 =>
object(WP_Post)
public 'ID'
public 'post_title'
public 'post_content'
1 =>
object(WP_Post)
public 'ID'
public 'post_title'
public 'post_content'
2 =>
object(WP_Post)
public 'ID'
public 'post_title'
public 'post_content'
3 =>
object(WP_Post)
public 'ID'
public 'post_title'
public 'post_content'
4 =>
object
public 'Donor'
public 'date'
public 'post_content'
And it goes on ...... I am trying to group this into first, second, third and fourth Quarter based on a date
meta field ie; first quarter is the first three months (Jan, Feb ,March ), second quarter will be the next three and so on and give headings ,'First Quarter ,'Second Quarter ' etc:-
I achieved this by
<h3> First Quarter </h3>
<?php
foreach($posts as $q1) {
$donor_date = get_post_meta($q1->ID,'donor-date',true);
$donor_month = date('m',strtotime($donor_date));
if(!in_array($donor_month,array('01','02','03'),true)) continue;
?>
<tr><td> <?php echo date('d/m/Y',strtotime($donor_date)); ?> </td></tr>
<?php endforeach; ?>
<h3> Second Quarter </h3>
<?php
foreach($posts as $q2) {
$donor_date = get_post_meta($q2->ID,'donor-date',true);
$donor_month = date('m',strtotime($donor_date));
if(!in_array($donor_month,array('04','05','06'),true)) continue;
?>
<tr><td> <?php echo date('d/m/Y',strtotime($donor_date)); ?> </td></tr>
<?php endforeach; ?>
and so on ...... the problem with this approach is that the headings ( First Quarter, Second Quarter ... ) will be there even if there is not data that meets the given condition . Is there a way to conditionally show and hide the headers too and a better method for sorting ( refactor) .......
Thanks in advance ........
You'll need to check the values in the array before starting any output.
I'd suggest doing this by saving the data to be displayed in an array instead of printing it immediately. Also, assuming
$posts
is the same in everyforeach
, you will only need to loop once.Example with step-by-step instructions in the comments
I'm not sure where your
<table>
element is created,because at the moment the<h3>
s are added between<tr>
s which is incorrect - however this mirrors the code you posted, so you should know how to work around that yourself!Put the header inside the for loop and validate the month with if and else if statements to select which header display use one foreach statement