原因是get_the_modified_author()
不起作用是因为它依赖于在WordPress循环中使用。wp_get_recent_posts()
不设置全局post对象。下面是一个基于原始代码的完整示例get_the_modified_author()
用一些简单的代码来获取最后一个编辑帖子的人的名字(这基本上是get_the_modified_author()
是否):
/**
* Add a widget to the dashboard.
*
* This function is hooked into the \'wp_dashboard_setup\' action below.
*/
function example_add_dashboard_widgets() {
wp_add_dashboard_widget(
\'example_dashboard_widget\', // Widget slug.
\'Example Dashboard Widget\', // Title.
\'example_dashboard_widget_function\' // Display function.
);
}
add_action( \'wp_dashboard_setup\', \'example_add_dashboard_widgets\' );
function example_dashboard_widget_function() {
$items_to_show = 10;
$counter = 0;
$recent_posts = wp_get_recent_posts( [
\'post_status\' => \'publish\',
\'numberposts\' => \'50\', // More than we want, but tries to ensure we have enough items to display.
\'post_type\' => \'post\'
] );
echo \'<table>
<tr>
<th>Post Title</th>
<th>Author</th>
<th>Moderated by</th>
</tr>\';
foreach ( $recent_posts as $recent ) {
$post_author = get_user_by( \'id\', $recent[\'post_author\'] );
$last_user_id = get_post_meta( $recent[\'ID\'], \'_edit_last\', true );
$last_user = get_userdata( $last_user_id );
// Bail out of the loop if we\'ve shown enough items.
if ( $counter >= $items_to_show ) {
break;
}
// Skip display of items where the author is the same as the moderator:
if ( $post_author->display_name === $last_user->display_name ) {
continue;
}
echo \'<tr><td><a href="\' . get_permalink( $recent[\'ID\'] ) . \'" title="Read: \' .
esc_attr( $recent[\'post_title\'] ).\'" >\' . $recent[\'post_title\'].\'</a></td>\';
echo \'<td>\'. esc_html( $post_author->display_name ) .\'</td>\';
echo \'<td>\'. esc_html( $last_user->display_name ) .\'</td></tr>\';
$counter++;
}
echo \'</table>\';
}
Edit based on feedback from comment: 此代码跳过以下项目的显示:
$post_author->display_name === $last_user->display_name
. 但这并不是最有效的代码,因为我们查询的项目比需要的多。之所以这样做,是因为我们将跳过一些项目,并希望(尝试)确保至少有10个项目要显示(
$items_to_show
= 10) 。