如何在WordPress循环中排除受密码保护的帖子

Kev*_*vin 6 wordpress

我有一个支持密码保护条目的自定义帖子类型.在使用新WP_Query对象的自定义循环中,我想从结果中排除那些受密码保护的帖子.为了做到这一点,我需要设置什么参数?我正在使用WordPress 3.2.1的最新主干版本.

Cod*_*ver 12

我提出这个问题,我在寻找同样的问题.但是,我逐行阅读WP_Query文档,然后发现非常简单的解决方案,这只是为'has_password' => false查询添加参数$args

所以代码如下......

$args  = [
    'post_type'      => [ 'post', 'page' ],
    'posts_per_page' => 3,
    'post__not_in'   => get_option( 'sticky_posts' ),
    'has_password'   => FALSE
];
Run Code Online (Sandbox Code Playgroud)

在这里你可以看到我已经排除StickyPassword Protected发布.

  • 所有建议使用SQL的答案都很危险,不应该使用WordPress 3.9+.这是排除受密码保护的帖子的内置方式. (4认同)
  • 是的!这是这样做的方法。 (2认同)

小智 8

我真的很喜欢凯文的方法,但我稍微调整了一下:

// 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' );
Run Code Online (Sandbox Code Playgroud)


vzw*_*ick 0

您是否查看过WP_Query 的post_status 参数

“受保护”似乎是一个很好的排除候选者。

编辑:好的,看来您必须修改 where 子句才能实现您想要的:

// 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' );
Run Code Online (Sandbox Code Playgroud)