// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
// exclude password protected
$where .= " AND post_password = ''";
return $where;
}
if (!is_single()) { add_filter( 'posts_where', 'filter_where' ); }
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );
6
我真的很喜欢凯文的方法,但我稍微调整了一下:
// Create a new filtering function that will add our where clause to the query
function my_password_post_filter( $where = '' ) {
// Make sure this only applies to loops / feeds on the frontend
if (!is_single() && !is_admin()) {
// exclude password protected
$where .= " AND post_password = ''";
}
return $where;
}
add_filter( 'posts_where', 'my_password_post_filter' );
5 回答
我提出这个问题,我在寻找同样的问题 . 但是,我逐行阅读WP_Query文档,然后发现非常简单的解决方案,这只是将
'has_password' => false
参数添加到查询$args
所以代码如下......
在这里你可以看到我排除了
Sticky
和Password Protected
帖子 .你看过WP_Query的post_status argument了吗?
“受保护”似乎是排除的好选择 .
Edit: 好的,似乎你必须修改where子句才能达到你想要的效果:
我真的很喜欢凯文的方法,但我稍微调整了一下:
经过一段时间的游戏,我发现posts_where过滤器对我想做的事情有点过于干扰,所以我提出了另一种选择 . 作为我为自定义帖子类型附加的“save_post”操作的一部分,我添加了以下逻辑;
这样做是在选项表中保存一个post id的数组,其中的帖子受密码保护 . 然后在自定义查询中,我只是将此数组作为
post__not_in
选项的一部分传递,例如这样,我可以从存档页面中排除受保护的帖子,但仍允许用户登陆受密码保护的页面以输入密码 .
除了@Peter Chester的回答:
您可能还想从
Previous Post
和Next Post
链接中排除受密码保护的帖子,如果您在帖子页面的底部有这些帖子 .为此,您可以将排除项添加到
get_previous_post_where
和get_next_post_where
钩子中 .