2013-04-25 50 views
1

我想顯示在我的單一職位視圖下的3個職位(我有自定義職位類型設置,所以希望此查詢工作在所有單個帖子頁面不管帖子類型如何)。WordPress的 - 顯示3相關的職位,無論職位類型,自定義或其他

但是,下面的代碼,我沒有得到任何相關的職位顯示。當我刪除.
'&exclude=' . $current
我得到3相關帖子顯示,但與當前職位是其中之一。因此,爲什麼我添加'排除',但我不明白爲什麼它不顯示任何時候我添加此。

任何幫助將不勝感激。 感謝

<?php 

$backup = $post; 
$current = $post->ID; //current page ID 

global $post; 
$thisPost = get_post_type(); //current custom post 
$myposts = get_posts('numberposts=3&order=DESC&orderby=ID&post_type=' . $thisPost . 
'&exclude=' . $current); 

$check = count($myposts); 

if ($check > 1) { ?> 
<h1 id="recent">Related</h1> 
<div id="related" class="group"> 
    <ul class="group"> 
    <?php 
     foreach($myposts as $post) : 
      setup_postdata($post); 
    ?> 
     <li> 
      <a href="<?php the_permalink() ?>" title="<?php the_title() ?>" rel="bookmark"> 
       <article> 
        <h1 class="entry-title"><?php the_title() ?></h1> 
        <div class="name-date"><?php the_time('F j, Y'); ?></div> 
        <div class="theExcerpt"><?php the_excerpt(); ?></div> 
       </article> 
      </a> 
     </li> 

    <?php endforeach; ?> 
    </ul> 
<?php 
    $post = $backup; 
    wp_reset_query(); 
?> 

</div><!-- #related --> 
<?php } ?> 

回答

3

而不是使用get_posts(的),你可以使用WP_Query

<?php 

// You might need to use wp_reset_query(); 
// here if you have another query before this one 

global $post; 

$current_post_type = get_post_type($post); 

// The query arguments 
$args = array(
    'posts_per_page' => 3, 
    'order' => 'DESC', 
    'orderby' => 'ID', 
    'post_type' => $current_post_type, 
    'post__not_in' => array($post->ID) 
); 

// Create the related query 
$rel_query = new WP_Query($args); 

// Check if there is any related posts 
if($rel_query->have_posts()) : 
?> 
<h1 id="recent">Related</h1> 
<div id="related" class="group"> 
    <ul class="group"> 
<?php 
    // The Loop 
    while ($rel_query->have_posts()) : 
     $rel_query->the_post(); 
?> 
     <li> 
     <a href="<?php the_permalink() ?>" title="<?php the_title() ?>" rel="bookmark"> 
      <article> 
       <h1 class="entry-title"><?php the_title() ?></h1> 
       <div class="name-date"><?php the_time('F j, Y'); ?></div> 
       <div class="theExcerpt"><?php the_excerpt(); ?></div> 
      </article> 
     </a> 
     </li> 
<?php 
    endwhile; 
?> 
    </ul><!-- .group --> 
</div><!-- #related --> 
<?php 
endif; 

// Reset the query 
wp_reset_query(); 

?> 

試試上面的代碼並修改它爲自己的需要。修改爲適合您自己的標記。

+0

完美 - 謝謝@icethrill – fidev 2013-04-25 13:54:20

+0

沒問題,很高興能夠幫助! – MrZiggyStardust 2013-04-25 13:56:25

相關問題