2013-05-20 99 views
1

首先,我使用的是Wordpress。我有一個循環顯示一個稱爲events的自定義內容類型。我有後臺綁定到這個事件的用戶帳戶,並且我已經設置輸出它們綁定在author.php頁面(用戶配置文件頁面)上的許多事件。Wordpress中的PHP雙循環問題

通常在一個月內有多個事件,目前代碼設置爲單獨顯示事件div's。它看起來類似於這樣:

MAY 2013 
- 14 May 2013 Title of the event - City, State <link> 

MAY 2013 
- 17 May 2013 Title of the event - City, State <link> 

JUN 2013 
- 01 Jun 2013 Title of the event - City, State <link> 

如果有一個月以上的事件,我想這是所有事件的組合成一個「月」 div,並顯示如下所示:

MAY 2013 
- 14 May 2013 Title of the event - City, State <link> 
- 17 May 2013 Title of the event - City, State <link> 

JUN 2013 
- 01 Jun 2013 Title of the event - City, State <link> 

我無法弄清楚如何安排我的循環來獲得所需的輸出。這是我的代碼。

<?php 

    $currentAuthorId = $authorID; // gets the current authors ID of the user you are viewing 
    $today = getdate(); 

    $args = array(
     'post_type' => 'events', 
     'year' => $today['year'], 
     'order' => 'ASC' 
    ); 

    $eventQuery = new WP_Query($args); 

    while($eventQuery->have_posts()) : $eventQuery->the_post(); // Query for the events 
     $eventMonth = date('M', strtotime($eventQuery->post->post_date)); 
     $eventYear = date('Y', strtotime($eventQuery->post->post_date)); 

     echo '<div class="schedule-month">'; // Opening div for a month 
     echo '<h3>'.$eventMonth.'<span class="blue">'.$eventYear.'</span></h3>'; 
     echo '<ul>'; 

     if(get_field('event_performers')) {  // Using ACF (advanced custom fields) I check if there are performer/users tied to the events 
      while(has_sub_field('event_performers')) { 
       $performer = get_sub_field('performer'); 
       $uid = $performer['ID']; 


       if($currentAuthorId == $uid) {  // Match the current author to only the events he/she is tied to 
        $eventDate = date('d M Y', strtotime($eventQuery->post->post_date)); 
        $city = get_field('city'); 
        $state = get_field('state'); 

        echo '<li>';  // Loop through all events with that author and display 
        echo ' <span class="blue">'.$eventDate.'</span>'; 
        echo ' <p>'.$eventQuery->post->post_title.' - </p>'; 
        echo ' <span class="light">'.$city.', '.$state.'</span>'; 
        echo ' <a href="'.$eventQuery->post->guid.'">view event<span class="arrow"></span>'; 
        echo ' </a>'; 
        echo '</li>'; 
       } 
      } 
     } 

     echo '</ul>'; 
     echo '</div>'; 

    endwhile; 

?> 

我知道我需要存儲變量的檢查,如果是同一個月,但我不知道如何正確地安排它來顯示我需要什麼。

任何幫助,非常感謝。

回答

1
$tempMonth = ''; 
$tempYear = ''; 
while($eventQuery->have_posts()) : $eventQuery->the_post(); // Query for the events 
    $eventMonth = date('M', strtotime($eventQuery->post->post_date)); 
    $eventYear = date('Y', strtotime($eventQuery->post->post_date)); 

    if($tempMonth != $eventMonth || $tempYear != $eventYear) 
    { 
     $tempMonth = $eventMonth; 
     $tempYear = $eventYear; 
     echo '<div class="schedule-month">'; // Opening div for a month 
     echo '<h3>'.$eventMonth.'<span class="blue">'.$eventYear.'</span></h3>'; 
     echo '<ul>'; 
    }