wordpress 使用帖子 ID 查询帖子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11153741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Query post using post id
提问by Salvatore Dibenedetto
SSomeone can tell me what's the best way to get a post using it's id?
S有人可以告诉我使用它的 id 获取帖子的最佳方式是什么?
I'am using this:
我正在使用这个:
$query = query_posts('post_id='.$_GET['php_post_id']);
global $post;
foreach ($query as $post):
$query = query_posts('post_id='.$_GET['php_post_id']); 全球 $post;
foreach ($query as $post):
do stuff...
做东西...
This is returning an array with all post
这是返回一个包含所有帖子的数组
回答by Grávuj Miklós Henrich
get_post( $post_id, $output );
So in practice will look like:
所以在实践中看起来像:
$my_id = 7;
$post_id_7 = get_post($my_id);
Further reference about the post's parameters and fields, here: http://codex.wordpress.org/Function_Reference/get_post
有关帖子参数和字段的进一步参考,请访问:http: //codex.wordpress.org/Function_Reference/get_post
Update:It's the best practicewhen you need to get a single post by id, no cicles required.
更新:当您需要通过 id 获取单个帖子时,这是最佳实践,不需要 cicles。
回答by Jeremy Quick
You can create a query like so:
您可以像这样创建查询:
$rd_args = [
'ID' => $postId
];
$query = new WP_Query($rd_args);
And then you can retrieve the post from the query. Or set it to the global query and loop over it:
然后您可以从查询中检索帖子。或者将其设置为全局查询并循环遍历它:
$GLOBALS['wp_query'] = $query;
while ( have_posts() ) : the_post();
回答by Mr. Genesis
Change post_id=
to p=
.
更改post_id=
为p=
。
$setQuery = 'p='.$_GET['php_post_id'];
query_posts($setQuery);
Click in this link to see: Retrieve a Particular Post
单击此链接查看:检索特定帖子
回答by Subhajit
Here is the code to fetch post using query_post if you know the ID.
如果您知道 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();
}
?>
回答by icynets
If you are looking to get a single post with an ID you already know or getting from another source, i'll suggest the below code.
如果您希望获得带有您已经知道的 ID 或从其他来源获得的 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.