2

SSomeone 可以告诉我使用 id 获取帖子的最佳方式是什么?

我正在使用这个:

$query = query_posts('post_id='.$_GET['php_post_id']); 全球 $post;
foreach ($query 作为 $post):

做东西...

这是返回一个包含所有帖子的数组

4

5 回答 5

3
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。

于 2012-06-22T09:46:04.203 回答
2

更改post_id=p=

$setQuery = 'p='.$_GET['php_post_id'];
query_posts($setQuery);

单击此链接可查看:检索特定帖子

于 2018-12-18T15:45:51.200 回答
2

如果您正在寻找具有您已经知道的 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. 
于 2016-11-12T22:13:46.110 回答
1

您可以像这样创建查询:

  $rd_args = [
       'ID' => $postId
  ];

  $query = new WP_Query($rd_args);

然后您可以从查询中检索帖子。或者将其设置为全局查询并循环它:

$GLOBALS['wp_query'] = $query;

while ( have_posts() ) : the_post();
于 2018-07-05T15:36:58.713 回答
0

如果您知道 ID,这是使用 query_post 获取帖子的代码。

<?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();
    }
?>
于 2012-06-22T09:45:29.967 回答