$ wpdb返回重复的帖子

时间:2015-06-13 21:46:46

标签: php wordpress wpdb

我创建了一个短代码,显示用户上次登录后创建的帖子。短代码工作正常,但我不知道为什么,但我收到7个重复的帖子。因此,对于测试,我创建了一个名为“Sample Article”的帖子,当我回复帖子的标题时,我得到了这个结果。

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

简码

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' );

先谢谢你的帮助......

1 个答案:

答案 0 :(得分:1)

没关系,我自己解决了。在阅读$wpdb的WordPress Codex时,我看到如果我使用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_K); foreach ($pageposts as $post) { echo $post->post_title; } } add_shortcode( 'latest_posts_after_last_login', 'latest_posts_after_last_login' ); ,它将删除重复项并解决了我的问题。

如果它对任何人有帮助,这是我的工作代码:

@IBOutlet var yConstraint: NSLayoutConstraint