2012-07-07 214 views
0

對不起,令人困惑的標題。我在wordpress中顯示帖子列表,並使用foreach顯示來自每個帖子的圖像,標題等。然後我需要的是每個帖子都有一個導航,它使用錨點在同一頁面中提供到其他帖子的鏈接。foreach中的foreach在wordpress中獲取的值來自第一個foreach

我在第一個內部創建了另一個foreach,它再次抓取相同的帖子並生成導航。這一切都正常工作,除了每個導航鏈接的值對於每個帖子中的每個鏈接都是相同的。

例如,如果帖子被稱爲post1和post2,post1中的導航應該有一個鏈接到post1和post2,但兩個鏈接都轉到post1。同樣POST2內的導航應該有一個鏈接到POST1和POST2而是兩個鏈接去POST2:

//first foreach gets all the posts 

<?php 
$portfolioItems = array('numberposts' => 10, 'order'=> 'DESC', 'orderby' => 'title', 'category' => 4); 
$postslist = get_posts($portfolioItems); 
foreach ($postslist as $post) : setup_postdata($post); ?> 



// navigation which grabs the same posts and creates a list out of them 

<ol> 
<?php $portfolioNav = array('numberposts' => 10, 'order'=> 'DESC', 'orderby' => 'title', 'category' => 4); 
$postsnav = get_posts($portfolioNav); 
foreach ($postsnav as $postnav) : setup_postdata($postnav); ?> 
<li><a href="<?php the_field('portfolio_anchor'); ?>"><?php the_field('portfolio_anchor'); ?></a></li> 
<?php endforeach; ?> 
</ol> 


// The data getting pulled from the first foreach 
<div id="<?php the_field('portfolio_anchor'); ?>"></div> 
<h3><?php the_title(); ?></h3> 
<img src="<?php the_field('main_image'); ?>" /> 

<?php endforeach; ?> 
+0

也許我錯過了一些東西,但沒有理由有第二個循環。所以刪除foreach&get_posts。它應該工作然後 – dciso 2012-07-07 18:43:55

+0

我想我需要第二個foreach創建鏈接到其他職位,否則每個導航列表將只有1個鏈接 - 一個鏈接本身。 – 2012-07-07 18:47:55

+0

好的,那麼在第二個循環中重複使用$ postslist。沒有必要再次召回get_posts – dciso 2012-07-07 18:52:57

回答

0

管理使用query_posts,而不是get_posts解決這個問題:

<?php query_posts('category_name=Portfolio&posts_per_page=10&orderby=title&order=DESC'); ?> 
    <?php while (have_posts()) : the_post(); ?> 

那麼對於嵌套查詢我也做了同樣的事情,但在它的末尾添加wp_reset_postdata所以它沒有覆蓋原來的查詢:

 <!-- navigation nested query --> 
    <div class="row"> 
    <div class="span12 foliodivider" style="display: block;"> 
    <ol> 
    <?php $navNumber = 1; ?> 
    <?php $my_query = new WP_Query('category_name=Portfolio&posts_per_page=10&orderby=title&order=DESC'); ?> 
    <?php while ($my_query->have_posts()) : $my_query->the_post(); ?> 
    <li><a href="#<?php the_field('portfolio_anchor'); ?>"><?php echo $navNumber; $navNumber++; ?></a></li> 
    <?php endwhile; ?> 
    <?php wp_reset_postdata(); ?> 
    </ol> 
    </div> 
</div> 
<!-- navigation nested query end--> 

然後finaly添加的最後ENDWHILE在很我完成後使用第一個查詢結束:

<div id="<?php the_field('portfolio_anchor'); ?>"></div> 
    <h3><?php the_title(); ?></h3> 
    <img src="<?php the_field('main_image'); ?>" /> 
    <?php endwhile; ?>