WordPress wp_query + 过滤结果(无自定义文件) + next_post_link()



我做了广泛的搜索,但找不到答案(也许我没有使用正确的搜索词?

无论如何,这是我想要完成的:

我正在使用wp_query返回已发布的用户提交的帖子。我一次显示一个帖子并使用next_posts_link()让用户前进到下一篇文章。这一切都工作正常。我还使用wp-postratings插件对用户进行评分。我只想显示用户尚未评分的帖子。为此,我使用:

check_rated_username($post->ID)

这部分实际上也在工作。到目前为止,我的代码如下所示:

$my_query = new WP_Query( array (
'posts_per_page' => 1,
'orderby'        => 'rand',
'post_status'    => 'publish',
));
if ( $my_query->have_posts() ) : 
while ( $my_query->have_posts() ) : $my_query->the_post(); 
$rated = check_rated_username($post->ID);
if (!$rated) : ?>
<?php //the_title() etc. Show post details (it's long so I'm not going to post the whole thing, but the post details are showing up fine) ?>
<?php next_posts_link('Next &rarr;', 10); ?>
<?php endif; ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); endif; ?>

问题next_posts_link() 检索满足wp_query中设置的参数的帖子(因此不是"if (!rated)"语句的一部分。 在某些情况下,当我单击"下一步"时,它会显示一个空白页 - 该特定用户已经评分的帖子。

如何设置它,以便我在每个页面上显示用户尚未评级的帖子,并允许用户通过单击"下一步"按钮导航到下一个未评级的帖子?我并没有与我想出的方法结婚。我只需要达到这个最终结果。

谢谢!

您可以做的是首先获取用户评分的所有帖子 id:s,然后您可以在查询中添加post__not_in。它可能看起来像这样:

<?php 
/* Get all posts id:s that current user has rated */
$user_ratings = $wpdb->get_results( $wpdb->prepare( "SELECT rating_postid FROM {$wpdb->ratings} WHERE rating_userid = %d", get_current_user_id() ) ); ?>
<?php
/*Set up an empty array for save id:s in */
$post_not_in = array();
/* Check if $userRating has any values, if so loop thru and put the id into the array */
if($user_ratings){
foreach($user_ratings as $user_rating){
$post_not_in[] = $user_rating->rating_postid;
}
}
?>
<?php
/* The loop */
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'post_status' => 'publish',
'post__not_in' => $post_not_in
);
$my_query =  new WP_Query($args);?>
The rest of your code

这样,循环中只有当前用户尚未评级的帖子。

最新更新