该函数如何获取最近一篇文章的id?

时间:2017-01-06 作者:James

这是一个函数,它完成了我需要它做的事情。是别人写的。我想了解它是如何做到这一点的。(更多信息将添加到it FYI中。)

这里的目标是获取最新帖子的id。我理解WordPress函数部分正在做什么。我不明白是怎么设置的$thePostID WordPress函数找到第一篇帖子后。具体而言,[0]和[ID]。

有人能解释一下吗?

function prepare_payment() {
  $recent_posts = wp_get_recent_posts( array( \'numberposts\' => \'1\' ) );
  $thePostID = $recent_posts[0][\'ID\'];
  echo $thePostID;
}

1 个回复
最合适的回答,由SO网友:Dave Romsey 整理而成

prepare_payment() 正在呼叫wp_get_recent_posts() 默认情况下,返回post数组。在这种情况下,由于$numberposts 参数设置为1.

$recent_posts 保存由返回的帖子数组wp_get_recent_posts(). 以下行正在设置$thePostID 中第一个帖子的ID$recent_posts 阵列(arrays are zero indexed):

$thePostID = $recent_posts[0][\'ID\'];
最后,使用该行回显IDecho $thePostID;

编辑:以下是返回的数组示例wp_get_recent_posts(), 它本身就是get_posts().`

Array
(
    [0] => Array
        (
            [ID] => 418
            [post_author] => 2
            [post_date] => 2025-01-01 00:00:00
            [post_date_gmt] => 2025-01-01 00:00:00
            [post_content] => This post is scheduled to be published in the future.

It should not be displayed by the theme.
            [post_title] => Scheduled
            [post_excerpt] => 
            [post_status] => future
            [comment_status] => open
            [ping_status] => closed
            [post_password] => 
            [post_name] => scheduled
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2016-04-11 04:28:22
            [post_modified_gmt] => 2016-04-11 04:28:22
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://wpthemetestdata.wordpress.com/?p=418
            [menu_order] => 0
            [post_type] => post
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
        )

)
您可以通过将一个简单的调试语句添加到prepare_payment():

function prepare_payment() {
  $recent_posts = wp_get_recent_posts( array( \'numberposts\' => \'1\' ) );

    // Temporary debugging statement
    print_r( $recent_posts );

  $thePostID = $recent_posts[0][\'ID\'];
  echo $thePostID;
}