2016-11-04 40 views
0

我有下面的代碼缺少一部分以確定要使用哪個'post'。向wordpress循環添加新參數

HTML

<?php if (have_posts()) : ?> 
<?php while (have_posts()) : the_post(); ?> 
    <?php 
      $postAlign = get_post_meta(get_the_ID(), 'postType', true); 

      if ($postAlign == 'Lsection') { 
       get_template_part('article' , 'Lsection');  
      } 
      else { 
       get_template_part('article' , 'Rsection'); 
      } 
      else { 
       get_template_part('article' , 'Fsection'); 
      } 
     ?> 
<?php endwhile; ?> 
<?php endif; ?> 

我要的是 後話了具有 'Lsection' 使用article-Lsection.php, 後話了具有 'Rsection' 使用article-Rsection.php, 。如果postAlign的postAlign該帖子有postAlign'Fsection'使用article-Fsection.php

我知道我必須有一個其他的如果或某些類似功能invdved

回答

0

一個else塊不應該跟着另一個else塊。請參閱下面修改的if-else if塊。有關格式化控制結構的更多信息,請參閱php.net頁:elseif/else if

if ($postAlign == 'Lsection') { 
    get_template_part('article' , 'Lsection');  
} 
else if ($postAlign == 'Rsection') { 
    get_template_part('article' , 'Rsection'); 
} 
else { 
    get_template_part('article' , 'Fsection'); 
} 

你也可以使用一個switch聲明 - 例如:

switch($postAlign) { 
    case 'Lsection': 
    case 'Rsection': 
     get_template_part('article' , $postAlign);  
     break; 
    default: 
     get_template_part('article' , 'Fsection'); 
     break; 
} 

或者只是簡化甚至更多:

if ($postAlign == 'Lsection' || $postAlign == 'Rsection') { 
    get_template_part('article' , $postAlign);  
} 
else { 
    get_template_part('article' , 'Fsection'); 
} 

另外,是否有一個原因,您正在使用alternate syntax for control structures和多餘的關閉/開放php標籤?您應該能夠簡化它,就像這樣:

<?php 
//if (have_posts()) { // 
    while (have_posts()) { 
     the_post(); 
     $postAlign = get_post_meta(get_the_ID(), 'postType', true); 

     if ($postAlign == 'Lsection' || $postAlign == 'Rsection') { 
      get_template_part('article' , $postAlign);  
     } 
     else { 
      get_template_part('article' , 'Fsection'); 
     } 
    }//end while 
//}//end if 
//only need one closing php tag down here: 
?> 

編輯: 爲了證明這一點,看到this PHPfiddle。隨意創建一個帳戶,並與代碼玩。請注意,它根據$postAlign的值調用get_templatepart()以及各種第二參數。

+0

全部三項工作謝謝 – user3550879

+0

不錯 - 請看我在底部添加的額外代碼建議,以簡化整個代碼 –

+0

儘管在我的WordPress管理員中使用了不同的postAlign(Lsection等),仍然遇到一些問題,他們都使用文章-Fsection – user3550879