获取最新博客文章的当前年份

所以我在一个获取 5 个最新帖子的方法中有以下查询。


public function get_most_recent()

{

    return BlogPost::get([

        'post_status' => 'publish',

        'order' => 'DESC',

        'orderby' => 'date',

        'posts_per_page' => 5,

    ]);

}

如何获取最新的发布年份?我有一种使用日期('Y')获取当前年份的方法,但我想获取最新的帖子年份。我该怎么做呢?


这是我的方法:


public function get_most_recent_year()

{

    $posts = $this->get_most_recent();


    foreach ($posts as $post) {

        var_dump($post);

    }

}

如果可能的话,我想瞄准类似的东西$year = get_most_recent_year();


更新:


var_dump($post) 给了我以下结构:


对象

-受保护的'post'=>

--对象

--私有'日期'=>

-----对象

------公共'日期'=>字符串'2017-09-14 09:45:53.000000 '


php


蓝山帝景
浏览 72回答 3
3回答

临摹微笑

解析日期并从中获取年份。public function get_most_recent_year(){    $posts = $this->get_most_recent();    if (empty($posts)) {        return 0;    }    $post = $posts[0];    $year = $post[0]->post->date->format('Y');    return $year;}

MMMHUHU

看起来您正在使用 WordPress。您可以使用get_the_date()来获取帖子的日期。第一个参数是 PHP 日期格式:$post_year = get_the_date('Y', $latest_post_id);

Cats萌萌

要获得时间,您可以使用以下语句。只需简单地解析日期<?php $time = date("Y", strtotime($row['PostDate'])); ?>
打开App,查看更多内容
随时随地看视频慕课网APP