$wpdb returns duplicate posts

I have created a shortcode which shows the posts which were created after the user last logged in. The shortcode is working perfectly fine, but I am not sure why but I am getting 7 duplicate posts. So like for test I created a post named as “Sample Article”, and when I echo out the title of the post, I get this result.

Sample Article Sample Article Sample Article Sample Article Sample Article Sample Article Sample Article Sample Article

Shortcode

function latest_posts_after_last_login( $atts ) {

    global $wpdb, $current_user;

    $atts = shortcode_atts( array( 'post_type' => ''), $atts, 'latest_posts_after_last_login' );

    $post_type = $atts['post_type'];

    $last_login = get_user_meta( $current_user->ID, '_last_login_for_posts', true );

    $querystr = "
        SELECT $wpdb->posts.* 
        FROM $wpdb->posts, $wpdb->postmeta
        WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
        AND $wpdb->posts.post_status = 'publish' 
        AND $wpdb->posts.post_type = '%s' 
        AND $wpdb->posts.post_date > '%s'
        ORDER BY $wpdb->posts.post_date DESC
    ";

    $prepare = $wpdb->prepare($querystr, array($post_type , $last_login));

    $pageposts = $wpdb->get_results($prepare, OBJECT);

    foreach ($pageposts as $posts) {
        echo $posts->post_title;
    }

}
add_shortcode( 'latest_posts_after_last_login', 'latest_posts_after_last_login' );

Thanks for the help in advance …


Source: wpdb

Leave a Reply