我创建了一个短代码,显示用户上次登录后创建的帖子。这个短代码工作得很好,但我不知道为什么,但我得到了7个重复的帖子。就像测试一样,我创建了一个名为“示例文章”的帖子,当我呼出帖子的标题时,我得到了这个结果。
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\' );
提前感谢您的帮助。。。
最合适的回答,由SO网友:Fahad Sohail 整理而成
没关系,我自己解决的。阅读WordPress Codex时$wpdb, 我看到了如果我使用OBJECT_K
它将删除重复项,从而解决了我的问题。
如果这对任何人都有帮助,下面是我的工作代码:
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\' );