2017-08-09 58 views
1

我有一個WP_Query查詢CPT'項目'作者的詳細信息。從ACF中繼器領域獲取作者時,如果有多個作者,我想在它們之間添加單詞「and」。WP_Query中間的重置計數

在單個項目上工作得很好,但是當我查詢所有項目時,計數在子循環後不會重置。不知道是否需要重置計數和/或是否需要計算中繼器中的項目數量,如果大於2則運行代碼?

無論哪種方式,不知道如何做到這一點,希望有人可能會給我一些指針。

<?php 
    $args = array(
'post_type' => 'showcase', 
'posts_per_page' => -1, 
'orderby' => 'rand', 
); 
$projects = new WP_Query($args); 
?> 
<?php if($projects->have_posts()) : ?> 
<?php while($projects->have_posts()) : $projects->the_post() ?> 
    // some content here 
     <?php $i==1; while(have_rows('project_author')): the_row(); ?> 
     <?php if($i ==1) 
     { 
     echo "and"; 
     }; ?> 
     <?php the_sub_field('screenwriters_name'); ?> 
     <?php $i++; endwhile; ?> 
<?php endwhile ?> 
<?php endif ?> 
<?php wp_reset_postdata(); ?> 

THX

+0

你有一個聲明$ i == 1之前評論/ /一些內容爲真。我認爲你需要刪除一個相等的符號。 –

回答

1

嘗試設置$i爲1。您需要使用賦值運算符,而不是(單,而不是雙等號),當您使用等於運算符。

目前$i只有在運行$i++後纔會變爲1,這會導致一些意外的行爲。如果$i在代碼頂部正確設置爲1,則while循環內輸出'和'的if語句將在循環的第一次迭代中運行。

我看到的使用邏輯的另一個問題是'和'只會輸出一次,無論中繼器字段中有多少個作者。

有幾種方法可以解決這個問題。

溶液1 - 修補錯誤

<?php while ($projects->have_posts()) : $projects->the_post(); ?> 

    <?php $i = 1; // fix assignment 

    while(have_rows('project_author')): the_row(); 

     // run on all iterations of the loop except the first. 
     if ($i > 1) { 
      echo ' and '; // add space before and after string. 
     } 

     the_sub_field('screenwriters_name'); 

     $i++; 
    endwhile; ?> 
<?php endwhile; ?> 

解決方案2 - 處理該字段爲一個數組並使用內爆()

將該溶液感覺清潔劑箱。我們將檢索作者字段作爲數組而不是循環使用中繼器函數(have_rows()/the_row())。

<?php while ($projects->have_posts()) : $projects->the_post(); ?> 

    <?php $project_author = get_field('project_author'); 

    if ($project_author) { 

     // extract screenwriters_name values (the sub field name) from the fields array. 
     $screenwriter_names = array_column($project_author, 'screenwriters_name'); 

     // join elements of the array into a string. ' and ' is only used when more than one. 
     echo implode(' and ', $screeenwriter_names); 
    } ?> 
<?php endwhile; ?> 
+0

謝謝Nathan,第一個解決方案完美無缺! – Renegade