doucaishou0074 2017-08-06 05:44
浏览 30

获取最新的帖子ID无法按预期工作

I've trying to get the latest post ID in WordPress, but the two different methods I am using are returning different results.

FYI if I look in PHPmyAdmin I can see the latest post ID is 3000.

If I do this...

$args = array( 
    'post_type' => 'any'
);
$the_ID = get_posts($args);
$latest_ID = $the_ID[0]->ID;
echo $latest_ID;

...it returns 2999 instead of 3000. This is very odd.

But if I specify some post types in an array like this...

$args = array( 
    'post_type' => array('post', 'page', 'attachment')
);
$the_ID = get_posts($args);
$latest_ID = $the_ID[0]->ID;
echo $latest_ID;

...it returns 3000 which is the correct ID but also not very maintainable.

My understanding is that 'post_type' => 'any' should include all post types, and obviously I don't want to use the 2nd method because I'd have to update the array manually every time there is a new post type.

Is there a way around this? Or perhaps a better way of getting the latest post ID?

  • 写回答

2条回答 默认 最新

  • donglun7151 2017-08-06 05:50
    关注

    Use this code 100% working and tested:

    Note: When you register new post type then automatically will be add in below conditions.

    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;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用