get_most_recent_post_of_user()
云策文档标注
概述
get_most_recent_post_of_user() 函数用于获取指定用户的最新发布文章,通过遍历用户所属的所有站点,查找 post_date_gmt 最新的文章。
关键要点
- 参数:$user_id(整数,必需),表示用户ID。
- 返回值:数组,包含 blog_id、post_id、post_date_gmt 和 post_gmt_ts。
- 功能:遍历用户的所有博客,使用 SQL 查询获取每个博客中用户发布的最新文章,并比较 post_date_gmt 以确定全局最新文章。
- 依赖函数:get_blogs_of_user()、wpdb::get_row()、wpdb::get_blog_prefix()、wpdb::prepare()。
代码示例
function get_most_recent_post_of_user( $user_id ) {
global $wpdb;
$user_blogs = get_blogs_of_user( (int) $user_id );
$most_recent_post = array();
foreach ( (array) $user_blogs as $blog ) {
$prefix = $wpdb->get_blog_prefix( $blog->userblog_id );
$recent_post = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_date_gmt FROM {$prefix}posts WHERE post_author = %d AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1", $user_id ), ARRAY_A );
if ( isset( $recent_post['ID'] ) ) {
$post_gmt_ts = strtotime( $recent_post['post_date_gmt'] );
if ( ! isset( $most_recent_post['post_gmt_ts'] ) || ( $post_gmt_ts > $most_recent_post['post_gmt_ts'] ) ) {
$most_recent_post = array(
'blog_id' => $blog->userblog_id,
'post_id' => $recent_post['ID'],
'post_date_gmt' => $recent_post['post_date_gmt'],
'post_gmt_ts' => $post_gmt_ts,
);
}
}
}
return $most_recent_post;
}注意事项
- 此函数仅查询 post_type 为 'post' 且 post_status 为 'publish' 的文章,忽略其他类型或状态。
- 在多站点环境中,需要确保用户有访问相关博客的权限。
- 函数从 WordPress MU 3.0.0 版本引入,适用于多站点场景。
原文内容
Gets a user’s most recent post.
Description
Walks through each of a user’s blogs to find the post with the most recent post_date_gmt.
Parameters
$user_idintrequired-
User ID.
Source
function get_most_recent_post_of_user( $user_id ) {
global $wpdb;
$user_blogs = get_blogs_of_user( (int) $user_id );
$most_recent_post = array();
/*
* Walk through each blog and get the most recent post
* published by $user_id.
*/
foreach ( (array) $user_blogs as $blog ) {
$prefix = $wpdb->get_blog_prefix( $blog->userblog_id );
$recent_post = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_date_gmt FROM {$prefix}posts WHERE post_author = %d AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1", $user_id ), ARRAY_A );
// Make sure we found a post.
if ( isset( $recent_post['ID'] ) ) {
$post_gmt_ts = strtotime( $recent_post['post_date_gmt'] );
/*
* If this is the first post checked
* or if this post is newer than the current recent post,
* make it the new most recent post.
*/
if ( ! isset( $most_recent_post['post_gmt_ts'] ) || ( $post_gmt_ts > $most_recent_post['post_gmt_ts'] ) ) {
$most_recent_post = array(
'blog_id' => $blog->userblog_id,
'post_id' => $recent_post['ID'],
'post_date_gmt' => $recent_post['post_date_gmt'],
'post_gmt_ts' => $post_gmt_ts,
);
}
}
}
return $most_recent_post;
}
Changelog
| Version | Description |
|---|---|
| MU (3.0.0) | Introduced. |