2015-06-23 114 views
2

我想爲特寫類別添加一個Wordpress循環,用於排除當前帖子的帖子模板。從循環中排除當前帖子

我建議使用:

<?php 
global $wp_query; 
$cat_ID = get_the_category($post->ID); 
$cat_ID = $cat_ID[0]->cat_ID; 
$this_post = $post->ID; 
query_posts(array('cat' => $cat_ID, 'post__not_in' => array($this_post), 'posts_per_page' => 14, 'orderby' => 'rand')); 
?> 

但我無法得到它的工作。

我的循環目前看起來像這樣。

<div class="video"> 
    <?php 
     $catquery = new WP_Query('category_name=video&posts_per_page=4'); 
     while($catquery->have_posts()) : $catquery->the_post(); 
    ?> 

    <div> 
     <a href="<?php the_permalink(); ?>"> 
      <?php the_post_thumbnail(); ?> 
      <h2><?php the_title(); ?></h2> 
     </a> 
    </div> 

    <?php endwhile; ?> 

    <p class="more">M<br>O<br>R<br>E</p> 
</div> 

回答

2

試試這個代碼。

$postid = get_the_ID(); 
    $args=array(
     'post__not_in'=> array($postid), 
     'post_type' => 'post', 
     'category_name'=>'video', 
     'post_status' => 'publish', 
     'posts_per_page' => 4 

    ); 


    <div class="video"> 
     <?php 
      $catquery = new WP_Query($args); 
      while($catquery->have_posts()) : $catquery->the_post(); 
     ?> 

     <div> 
      <a href="<?php the_permalink(); ?>"> 
       <?php the_post_thumbnail(); ?> 
       <h2><?php the_title(); ?></h2> 
      </a> 
     </div> 

     <?php endwhile; ?> 

     <p class="more">M<br>O<br>R<br>E</p> 
    </div> 
+0

完美的作品謝謝你! –

-1

兩個代碼塊使用兩種不同的技術WordPress的定製環......第一個修改全局查詢,第二個創建新的自定義查詢。我在下面用你的循環模板概述了兩個。

示例以及建議的代碼,全局查詢:

遍歷循環代碼全局$ wp_query對象:

<div class="video"> 
<?php 
    global $wp_query; 
    $cat_ID = get_the_category($post->ID); 
    $cat_ID = $cat_ID[0]->cat_ID; 
    $this_post = $post->ID; 
    query_posts(array('cat' => $cat_ID, 'post__not_in' => array($this_post), 'posts_per_page' => 14, 'orderby' => 'rand')); 
?> 

<!-- use the global loop here --> 

<?php while (have_posts()) : the_post(); ?> 


    <div> 
     <a href="<?php the_permalink(); ?>"> 
      <?php the_post_thumbnail(); ?> 
      <h2><?php the_title(); ?></h2> 
     </a> 
    </div> 

<?php endwhile; ?> 

<p class="more">M<br>O<br>R<br>E</p 
</div> 

例與原代碼,自定義查詢

通過自定義查詢循環,添加'post__not_in':

<div class="video"> 
<?php 
    $catquery = new WP_Query( 'category_name=video&posts_per_page=4&post__not_in=' . $post->ID); 
    while($catquery->have_posts()) : $catquery->the_post(); 
?> 

    <div> 
     <a href="<?php the_permalink(); ?>"> 
      <?php the_post_thumbnail(); ?> 
      <h2><?php the_title(); ?></h2> 
     </a> 
    </div> 

    <?php endwhile; ?> 

    <p class="more">M<br>O<br>R<br>E</p> 
</div> 

對不起,如果我的原始答案不清楚,我最初認爲你是結合了兩個代碼塊。

1

使用

'post__not_in' => array($post->ID) 
+0

我該如何將這個添加到上面的循環中? –