2017-02-09 39 views
2

我有這個循環運行在我的WordPress的索引(index.php)頁面,它顯示我的帖子沒有問題。爲什麼我的Wordpress查詢不適用於非索引頁面?

但是,如果我嘗試在另一頁上使用此代碼,找不到帖子。

任何人都可以解釋爲什麼嗎?

Ta!

<?php 
     $args = array(
      'post_type' => 'post', 
       ); 
     $query = new WP_Query($args); 
     if ($query->have_posts()) : 
      // Start the Loop. 
      while (have_posts()) : the_post(); 
       get_template_part('content', get_post_format()); 

      endwhile; 
      // Previous/next post navigation. 
      twentyfourteen_paging_nav(); 

     else : 
      get_template_part('content', 'none'); 

     endif; 
    ?> 
+0

這個模板的名字是什麼? –

回答

1

只是一些重要的點這裏:

請添加wp_reset_postdata();每個自定義查詢之後。 https://codex.wordpress.org/Function_Reference/wp_reset_postdata

此外,只查詢發佈的帖子。 'post_status'=>'發佈'

<?php 
     $args = array(
      'post_type' => 'post', 
      'posts_per_page' => -1, 
      'post_status' => 'publish' 
       ); 
     $query = new WP_Query($args); 
     if ($query->have_posts()) : 
      // Start the Loop. 
      while ($query->have_posts()): 
       $query->the_post(); 
       get_template_part('content', get_post_format()); 
      endwhile; 
      // Previous/next post navigation. 
      twentyfourteen_paging_nav(); 

      // Reset post data 
      wp_reset_postdata(); 

     else : 
      get_template_part('content', 'none'); 

     endif; 
    ?> 
+0

啊,所以我只是缺少'$ query->;在我的while循環中,niceone。並感謝有關良好實踐的指針。 – jack

1

剛剛對您的代碼做了幾處修改,請試試這個。爲我工作。

<?php 
     $args = array(
      'post_type' => 'post', 
      'posts_per_page' => -1 
       ); 
     $query = new WP_Query($args); 
     if ($query->have_posts()) : 
      // Start the Loop. 
      while ($query->have_posts()): 

     $query->the_post(); 
       get_template_part('content', get_post_format()); 
          endwhile; 
      // Previous/next post navigation. 
      twentyfourteen_paging_nav(); 

     else : 
      get_template_part('content', 'none'); 

     endif; 
    ?> 
+0

謝謝anjana,你說得對,這工作的魅力! – jack

+0

謝謝傑克@jack和upvote也:) –

相關問題