2013-11-22 37 views
0

我已經註冊了一個自定義帖子類型和inisde我的檔案-myCPT.php我想檢索只是當前發佈的帖子。 這裏是我的存檔myCPT.php相關片段:檢查當前發帖

if(have_posts()){ 

$x = 1; 
while (have_posts()){ 
the_post(); 
    if (0 === (int) $post->post_parent) { 
    get_template_part('inc/post-format/content-debate'); 

} 

我如何添加這個循環中的條件來檢查目前公佈的職位和檢索只有一個(最近的一次)?這可能嗎 ?如果是這樣,我該怎麼做?

回答

0

我們可以直接檢索後在wp_query參數過濾選擇

<?php 
// The Query 
$args=array(
'post_type'=>'custom-post-type', 
'posts_per_page'=>1, 
'post_parent'=>'parent-page-id', 
'order'=>'DESC' 
); 
$the_query = new WP_Query($args); 
if ($the_query->have_posts()) { 
while ($the_query->have_posts()) { 
    $the_query->the_post();?> 

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

<?php }} 

wp_reset_postdata();?> 

所以也就沒有必要在循環內濾波的。 希望這有助於。

1

在循環中,您只獲得發佈的帖子,所以這不是您關心的問題。

如果你想在最後公佈後,之前if(have_posts())功能query_posts('posts_per_page=1&order=DESC&orderby=date&post_type=my_custom_post_type')

添加通過query_posts你可以很容易地修改你的循環。

編輯:

要檢索特別是一個職位,而不是循環使用get_posts

$posts = get_posts('posts_per_page=1&post_type=my_custom_post_type'); 

//do not use reserved variable name $post 
foreach($posts as $single_post) setup_postdata($single_post); 
    //you can use the_title(), the_content()... 
+0

如果我使用它,將只檢索最近發佈的帖子? – agis

+0

我試過這個,但對我不好,它從默認的博客文章中檢索最後一篇文章,而不是從我的CPT中找到,它也爲其他文章添加了分頁。 – agis

+1

檢索CPT,將其添加到query_posts參數'&post_type = my_custom_post_type'中。我不是百分百肯定的,你是否可以在使用循環時禁止顯示分頁鏈接(除了刪除分頁代碼),你可以嘗試'&paged = 0'或'&paged = 1'。通過一切手段,檢查我的編輯,我喜歡另一種解決方案,可能會在這種情況下足智多謀。 –