List latest posts in WP-Admin

All you need is a table with class="widefat" and get_posts(). Then you run through the results (if there are any) and print the table rows.

Here is a very simple example as a dashboard widget. Note the lack of I18n – it is not ready to use!

<?php
/**
 * Plugin Name: Last posts table
 * Plugin URI:  http://wordpress.stackexchange.com/q/71887/73
 */

add_action( 'wp_dashboard_setup', 'wpse_71887_register_dashboard_widget' );

function wpse_71887_register_dashboard_widget()
{
    wp_add_dashboard_widget(
        __FUNCTION__,
        'Last Posts',
        'wpse_71887_render_dashboard_widget'
    );
}

function wpse_71887_render_dashboard_widget()
{
    $header="
        <tr>
            <th>User</th>
            <th>Post</th>
            <th>Time</th>
        </tr>";

    print "<table class="widefat">
    <thead>$header</thead>
    <tfoot>$header</tfoot>
    <tbody>";

    // get 10 last private and published posts
    $posts = get_posts(
        array (
            'numberposts' => 10,
            'post_type'   => array ( 'post', 'page' )
        )
    );

    if ( ! $posts )
    {
        print '<tr><td cols="3">No posts found. <a href="'
            . admin_url( 'post-new.php' ) . '">Write one!</a>';
    }
    else
    {
        foreach ( $posts as $post )
        {
            printf(
                '<tr>
                    <td>%1$s</td>
                    <td><a href="%2$s">%3$s</a></td>
                    <td>%4$s ago</td>
                </tr>',
                esc_html( get_user_by( 'id', $post->post_author )->display_name ),
                get_permalink( $post->ID ),
                esc_html( $post->post_title ),
                human_time_diff( mysql2date( 'U', $post->post_date ) )
            );
        }
    }

    print '</table>';
}

Result

enter image description here

Leave a Comment