Wordpress:获取自定义类型的所有帖子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25237430/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:59:22  来源:igfitidea点击:

Wordpress: get all posts of a custom type

wordpress

提问by Michael

I have this strange issue. I want to fetch all posts that are of a custom type, here's my snippet.

我有这个奇怪的问题。我想获取所有自定义类型的帖子,这是我的片段。

$query = new WP_Query(array(
    'post_type' => 'custom',
    'post_status' => 'publish'
));


while ($query->have_posts()) {
    $query->the_post();
    $post_id = get_the_ID();
    echo $post_id;
    echo "<br>";
}

wp_reset_query();

This only gets me 6 of them, while I have more than 50 records matching that criteria in the database. Can anyone tell me where I have gone wrong?

这只会让我得到 6 个,而我在数据库中有超过 50 条符合该条件的记录。谁能告诉我我哪里出错了?

Many thanks!

非常感谢!

回答by jono

'posts_per_page' => -1,

'posts_per_page' => -1,

Add this to the WP_QUERY array of arguments and it should return all of the posts of this custom post type.

将此添加到 WP_QUERY 参数数组,它应该返回此自定义帖子类型的所有帖子。

回答by Andrea

This get all posts of a custom type using get_posts:

这使用以下方法获取自定义类型的所有帖子get_posts

$posts = get_posts([
  'post_type' => 'custom',
  'post_status' => 'publish',
  'numberposts' => -1
  // 'order'    => 'ASC'
]);

回答by mustra

You should never use:

你永远不应该使用:

'posts_per_page' => -1

It slow and not effective, if you are talking about SQL Query speeds. So it is much better to use some large integer.

如果您在谈论 SQL 查询速度,它会很慢且无效。所以最好使用一些大整数。

This is a performance hazard. What if we have 100,000 posts? This could crash the site. If you are writing a widget, for example, and just want to grab all of a custom post type, determine a reasonable upper limit for your situation.

这是性能风险。如果我们有 100,000 个帖子怎么办?这可能会导致网站崩溃。例如,如果您正在编写一个小部件,并且只想获取所有自定义帖子类型,请为您的情况确定一个合理的上限。

More details here: https://10up.github.io/Engineering-Best-Practices/php/#performance

更多细节在这里:https: //10up.github.io/Engineering-Best-Practices/php/#performance

回答by Bobadevv

The number of posts to return are set under settings > reading

返回的帖子数量在设置>阅读下设置

You can pass the number of posts for your query to return using.

您可以传递查询的帖子数以返回使用。

'posts_per_page' => 'number of posts'

回答by joseacat

It is advisable to use an integer instead of '-1' For example:

建议使用整数而不是 '-1' 例如:

'posts_per_page' => 999999,