>我创建了一个短代码,显示用户上次登录后创建的帖子。简码运行良好,但我不确定为什么,但我收到了 7 个重复的帖子。所以就像测试一样,我创建了一个名为"示例文章"的帖子,当我回显帖子的标题时,我得到了这个结果。
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' );
提前感谢您的帮助...
没
关系,我自己解决了。在阅读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' );