2012-06-22 190 views
2

SSomeone可以告訴我什麼是使用它的ID獲得帖子的最佳方式?查詢帖子使用帖子ID

我'使用該:

$查詢= query_posts( 'POST_ID =' $ _ GET [ 'php_post_id']); global $ post;
的foreach($查詢爲$後):

做的東西......

這是返回所有的數組後

回答

0

下面是代碼使用query_post如果你知道如何獲取後ID。

<?php 
    $my_query = query_posts('post_id=111&post_type=parks'); // in place of 111 you need to give desired ID. 
    global $post; 
    foreach ($my_query as $post) { 
     setup_postdata($post); 
     the_title(); 
     the_content(); 
    } 
?> 
+1

我一直在使用這一點,但不知道爲什麼返回所有職位的數組...我有固定與此:\t 'post', \t'post__in'=> array($ _ GET ['php_post_id']), \t); $ post_query = new WP_Query($ args); while($ post_query-> have_posts()):$ post_query-> the_post(); endforeach; –

+0

好吧然後。我希望你的問題現在得到解決? – Subhajit

+1

使用「p」參數而不是「post_in」來獲得一個必需的帖子! – dk1

1
get_post($post_id, $output); 

因此,在實踐中會是這樣的:

$my_id = 7; 
$post_id_7 = get_post($my_id); 

關於這篇文章的參數和字段進一步的參考,在這裏:http://codex.wordpress.org/Function_Reference/get_post

更新:這是最佳實踐當你需要通過id獲得一個單獨的帖子時,不需要任何cicles。

0

如果你正在尋找一個你已經知道或從其他來源獲得的ID的帖子,我會建議下面的代碼。

$args = array(
     'post_type' => 'post', 
     'post_status' => 'publish', 
     'p' => $id, // id of the post you want to query 
    ); 
    $my_posts = new WP_Query($args); 

    if($my_posts->have_posts()) : 

     while ($my_posts->have_posts()) : $my_posts->the_post(); 

      get_template_part('template-parts/content', 'post'); //Your Post Content comes here 

     endwhile; //end the while loop 

endif; // end of the loop.