2017-03-19 38 views
0

我對通過new WP_Query與隨機選擇的文章我的網頁部分的specifed數。問題是'posts_per_page'屬性不起作用。這裏是我的代碼:WordPress的 - WP_Query不加載後

<div id="featured"> 
    <?php 

     $args = array(
      'post_type' => 'post', 
      'orderby' => 'rand', 
      'posts_per_page' => 4, 
      'nopaging' => true, 
      ); 

     $the_query = new WP_Query($args); 
     if ($the_query->have_posts()) { 

      echo '<div style="table full">'; 

      while ($the_query->have_posts()) { 

       $the_query->the_post(); 

      ?> 

       <div class="featcell" style="background: url(<?php the_post_thumbnail_url(); ?>) center center"> 
        <a class="featartlink" href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a> 
       </div> 

      <?php 

      } 

      echo '</div>'; 

      wp_reset_postdata(); 

     } 

    ?> 
</div> 

上面的腳本的結果是腳本加載數據庫的所有帖子。腳本在單個帖子頁面下發布。我做錯了什麼?看起來一切正常,但事實並非如此!謝謝你的幫助。

回答

0

我不爲什麼,但一些測試後,我想也使用get_posts()功能,現在一切工作正常。我只是想知道爲什麼new WP_Query不想工作。

下面是正確的代碼與使用get_posts()功能。

<div id="featured"> 

    <?php 

     global $post; 

     $args = array( 

      'post_type' => 'post', 
      'posts_per_page' => 4, 
      'orderby' => 'rand', 

     ); 

     $rand_posts = get_posts($args); 
     if ($rand_posts) : 

      echo '<div style="table full">'; 

      foreach ($rand_posts as $post) : setup_postdata($post); ?> 

       <div class="featcell" style="background: url(<?php the_post_thumbnail_url(); ?>) center center"> 
         <a class="featartlink" href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a> 
       </div> 

      <?php endforeach; wp_reset_postdata(); 

      echo '</div>'; 

     endif; 

    ?> 

</div>