我试图在WordPress中获取最新的帖子ID,但我使用的两种不同的方法会返回不同的结果。
如果我查看PHPmyAdmin,我可以看到最新的帖子ID是3000。
如果我这样做......
$args = array(
'post_type' => 'any'
);
$the_ID = get_posts($args);
$latest_ID = $the_ID[0]->ID;
echo $latest_ID;
...它返回2999而不是3000.这很奇怪。
但是如果我在这样的数组中指定一些帖子类型......
$args = array(
'post_type' => array('post', 'page', 'attachment')
);
$the_ID = get_posts($args);
$latest_ID = $the_ID[0]->ID;
echo $latest_ID;
...它返回3000,这是正确的ID,但也不是很容易维护。
我的理解是' post_type' => '任何'应该包括所有帖子类型,显然我不想使用第二种方法,因为每次有新的帖子类型时我都必须手动更新数组。
有解决方法吗?或者也许是获取最新帖子ID的更好方法?
答案 0 :(得分:0)
使用此代码 100%工作和测试:
注意:当您注册新的帖子类型时,会自动添加以下条件。
function get_all_custom_post_types() {
$args = array( 'public' => true );
$output = 'objects'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
$post_types = array();
foreach ( $custom_post_types as $k => $post_type ) {
$post_types[] = $post_type->name;
}
return $post_types;
}
//print_r(get_all_custom_post_types()); // Array ( [0] => post [1] => page [2] => attachment [3] => product [4] => movies )
$args = array(
'post_type' => get_all_custom_post_types(),
'posts_per_page' => 10
);
$latest_cpt = get_posts($args );
//print_r($latest_cpt);
echo $latest_cpt[0]->ID;
答案 1 :(得分:0)
我发现了问题...
我的一个插件的帖子类型不公开。我把它从假变为真......
'public' => true
...现在如果我使用'post_type'=> 'any'它运作正常。