How to display the user that published a pending post?

The reason that get_the_modified_author() is not working is that it relies on being used within the WordPress loop. wp_get_recent_posts() does not set up a global post object. Here is a complete example based on your original code that replaces get_the_modified_author() with some simple code to get the name of the last person who edited the post (which is essentially what get_the_modified_author() does):

/**
 * 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: This code skips the display of items where $post_author->display_name === $last_user->display_name. It’s not the most efficient code though, since we’re querying more items than needed. This is done because we’ll skip some items and we want to (try) to ensure that there are at least 10 items to display ($items_to_show = 10).

Leave a Comment