<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
....
<?php endwhile; endif; ?>
可以理解上面的代碼。如果在wordpress中列表循環時幫助簡化
1,我可以刪除if和while條件嗎?直接使用<?php the_post();?>
。
2,我覺得if (have_posts())
和while (have_posts())
是一樣的,它是多餘的嗎?
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
....
<?php endwhile; endif; ?>
可以理解上面的代碼。如果在wordpress中列表循環時幫助簡化
1,我可以刪除if和while條件嗎?直接使用<?php the_post();?>
。
2,我覺得if (have_posts())
和while (have_posts())
是一樣的,它是多餘的嗎?
#1:調用the_post
沒有循環只會讓你顯示一個帖子。這可能是在單頁後理想的,例如,其中while
循環常被省略:
<?php
// single.php
if (have_posts()):
the_post();
?>
<p><?php the_content(); ?></p>
<? else: ?>
<p>No post found.</p>
<? endif ?>
#2:你是正確的 - 您發佈的片段是在其組合冗餘的if
和while
。
在大多數的主題,然而,這是用法:
<?php
if (have_posts()):
while (have_posts()): the_post();
?>
<div class="post"><?php the_content(); ?></div>
<?php endwhile; else: ?>
<p>No posts found.</p>
<?php endif; ?>
在這種情況下,使用if
語句可以讓你如果沒有帖子顯示在所有的東西。如果我們只是在該代碼中使用while
循環,那麼沒有任何帖子的頁面將不會輸出任何內容。
while(have_postS())
將自動評估have_postS()
由if(have_postS())
但因爲它是true
(因爲它是一個循環),如果你有循環和一些終止循環機制,然後用while
否則
一旦if
會做得更好。
我不知道Wordpress,但通過它的樣子,has_posts()返回一個真值或假值。該while
循環只執行,如果truthy值作爲條件通過,所以是的,你可以把它降低到whoopin 3線:
<?php while (have_posts()) : the_post(); ?>
....
<?php endwhile;?>
編輯:將這個作爲又一個例子,爲什麼複製粘貼代碼是壞...
哦,該死的。我發現這個代碼<?php if(have_posts()): while(have_posts()):the_post(); ?>在默認主題single.php中使用?這是多餘的!因爲在single.php中,它只有一個帖子,使用while循環無用。 – zhuanzhou 2011-04-22 05:44:47
是的,這是多餘的,但不用擔心。 [WordPress的默認主題也使用它](http://phpxref.com/xref/wordpress/wp-content/themes/twentyten/single.php.source.html#l15)。 – 2011-04-22 06:00:30