2010-04-28 25 views
2

我編輯了single.php以適應我的需求,它的工作原理。我只在循環的一部分留在其中如下:WordPress的側邊欄和循環php代碼扭曲對方

<?php if (have_posts()) : while (have_posts()) : the_post(); ?> 
    <div <?php post_class() ?> id="post-<?php the_ID(); ?>"> 
     <div class="entry"> 
     <?php the_content('<p class="serif">Read the rest of this entry &raquo;</p>'); ?> 
     <?php wp_link_pages(array('before' => '<p><strong>Pages:</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?>  </div> 
    </div> 
<?php endwhile; else: ?> 

    <p>Sorry, no posts matched your criteria.</p> 

<?php endif; ?> 

它只裏顯示的文字,就像我希望它。 我得到的問題是當我添加以下代碼作爲模板中的側邊欄使用時;

<?php query_posts('showposts=10'); ?> 
<?php while (have_posts()) : the_post(); ?> 
<a href="<?php the_permalink() ?>" rel="bookmark" title="Link to <?php the_title(); ?>"> 
<?php the_title(); ?></a><br /> 
<?php endwhile;?> 

它應該顯示最後10個職位的標題。但現在循環也顯示最新的(full0 10帖子,而不是隻屬於永久鏈接的一篇文章...我認爲一個變量左右正在被重用,需要休息..請注意,在single.php首先你得到「邊欄」代碼,然後你得到的「環」的代碼。

那麼,爲什麼WordPress的表現這樣?

+0

也許嘗試query_posts前rewind_posts()()在你的側邊欄 – DCrystal 2010-04-28 17:26:10

回答

5

之所以出現這種情況是因爲WordPress是全局變量的一個噩夢般的迷宮。 。query_posts()是最嚴重的罪犯之一,如果你檢查documentation此功能,你會看到,他們甚至不得不提醒你基本上不使用它:

重要說明

query_posts函數旨在用於修改主頁面 僅循環。這並不意味着 意味着在 頁面上創建輔助循環。如果要在主體之外創建單獨的 循環,則應創建單獨的WP_Query 對象並使用它們。使用 query_posts除 以外的其他循環可能會導致主循環 變得不正確,並可能顯示 不是 期望的內容。

他們已經增加了一些面向對象的東西,你現在可以使用替代,即WP_Query object(爲什麼他們沒有修改了「主」頁面擺脫荒謬的「的循環」的東西卻是值得商榷)。

你會想要做這樣的事情在側邊欄:

<?php 
$recentPosts = new WP_Query(); 
$recentPosts->query('showposts=10'); 
while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?> 

<a href="<?php the_permalink() ?>" rel="bookmark" 
    title="Link to <?php the_title(); ?>"> 
<?php the_title(); ?></a><br /> 
<?php endwhile;?> 

谷歌圍繞如何,如果你想使用more examples WP_Query。

+0

非常好,謝謝了詳盡的解釋! – theDoctor 2010-04-28 17:44:36

1
query('showposts = 10'); while($ recentPosts-> have_posts()): $ recentPosts-> the_post(); ?>

的rel =」 書籤 「標題=」 鏈接到「>

閱讀ü在側邊欄將代碼,你企圖得到的最後10個冠軍帖子顯示在側邊欄中,對嗎?如果你還是你可以只使用這行:

`<?php wp_get_archives('title_li=&type=postbypost&limit=10'); ?>