How to display page title+link of page created by user

To list all pages with title and permalink from one user you need $wpdb->get_results(). The following code is based on this answer: How to count current user’s pages?

First, we move the counter into a separate helper function; we might need it later again:

/**
 * Get all post IDs and titles of a type for a user.
 *
 * @param int $user_id
 * @param string $post_type 'page' (default), 'post', attachment, a custom post
 *                          type or 'any' (which excludes attachments)
 * @return array
 */
function t5_user_pages( $user_id, $post_type="page" )
{
    global $wpdb;
    $where = get_posts_by_author_sql( $post_type, true, $user_id );
    return $wpdb->get_results( "SELECT ID, post_title FROM $wpdb->posts $where" );
}

Now we use that function in our code:

if ( is_user_logged_in() )
{
    $user    = wp_get_current_user();
    $results = t5_user_pages( $user->ID );
    $count   = count( $results );

    if ( $count >= 1 )
    {
        print '<h2>Hello ' . esc_html( $user->display_name ) . '!</h2>
        <p>These are your pages:</p>
        <ul>';

        foreach ( $results as $result )
            printf( '<li><a href="https://wordpress.stackexchange.com/questions/97043/%1$s">%2$s</a></li>',
                get_permalink( $result->ID ),
                esc_html( $result->post_title )
            );

        print '</ul>';
    } else {
        // user is logged in but hasn't written anything
    }
}
else
{
    // user is not logged in
}

Leave a Comment