从加载的帖子中获取帖子ID

时间:2017-10-06 14:53:41

标签: php wordpress

我遇到一个简单的任务,给出了以这种方式检索的帖子:

$firstRowPost = PostService::GetLastPostByCategory('video');

        var_dump($firstRowPost); // this show me the post, and also the ID
        var_dump($firstRowPost->ID); // the ID is null :(


class PostService {
        public static function GetLastPostByCategory($categoryId) {
            $args = array(
                'posts_per_page' => 1,
                'cat' => $categoryId
            );
            $latestPost = get_posts($args);
            return $latestPost;
        }
     }

我可以获得整个帖子,但不能获得帖子ID

C:\xampp\apps\wordpress\htdocs\wp-content\themes\chester-app\mvc\controllers\index_controller.php:10:
array (size=1)
  0 => 
    object(WP_Post)[259]
      public 'ID' => int 52
      public 'post_author' => string '1' (length=1)
      public 'post_date' => string '2017-10-06 10:31:40' (length=19)
      public 'post_date_gmt' => string '2017-10-06 10:31:40' (length=19)
      public 'post_content' => string '<img src="http://localhost/wordpress/wp-content/uploads/2017/10/Cattura.png" alt="" width="1061" height="370" class="alignnone size-full wp-image-37" />

example post video' (length=172)
      public 'post_title' => string 'example post video' (length=18)
      public 'post_excerpt' => string '' (length=0)
      public 'post_status' => string 'publish' (length=7)
      public 'comment_status' => string 'open' (length=4)
      public 'ping_status' => string 'open' (length=4)
      public 'post_password' => string '' (length=0)
      public 'post_name' => string 'example-post-video' (length=18)
      public 'to_ping' => string '' (length=0)
      public 'pinged' => string '' (length=0)
      public 'post_modified' => string '2017-10-06 12:27:34' (length=19)
      public 'post_modified_gmt' => string '2017-10-06 12:27:34' (length=19)
      public 'post_content_filtered' => string '' (length=0)
      public 'post_parent' => int 0
      public 'guid' => string 'http://localhost/wordpress/?p=52' (length=32)
      public 'menu_order' => int 0
      public 'post_type' => string 'post' (length=4)
      public 'post_mime_type' => string '' (length=0)
      public 'comment_count' => string '0' (length=1)
      public 'filter' => string 'raw' (length=3)

我不明白为什么我无法获得帖子ID,

C:\xampp\apps\wordpress\htdocs\wp-content\themes\chester-app\mvc\controllers\index_controller.php:11:null

有什么帮助可以理解为什么? 提前致谢

1 个答案:

答案 0 :(得分:1)

由于您的数据实际上是一个对象数组,因此正确的语法应为:

$firstRowPost[0]->ID