首页 文章

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

提问于
浏览
5

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

5 回答

  • 9

    我提出这个问题,我在寻找同样的问题 . 但是,我逐行阅读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
    ];
    

    在这里你可以看到我排除了 StickyPassword Protected 帖子 .

  • 1

    你看过WP_Query的post_status argument了吗?

    “受保护”似乎是排除的好选择 .

    Edit: 好的,似乎你必须修改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' );
    
  • 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' );
    
  • 1

    经过一段时间的游戏,我发现posts_where过滤器对我想做的事情有点过于干扰,所以我提出了另一种选择 . 作为我为自定义帖子类型附加的“save_post”操作的一部分,我添加了以下逻辑;

    $visibility = isset($_POST['visibility']) ? $_POST['visibility'] : '';
    $protected  = get_option('__protected_posts', array());
    
    if ($visibility === 'password' && !in_array($post->ID, $protected)) {
        array_push($protected, $post->ID);
    }
    if ($visibility === 'public' && in_array($post->ID, $protected)) {
        $i = array_search($post->ID, $protected);
        unset($protected[$i]);
    }
    update_option('__protected_posts', $protected);
    

    这样做是在选项表中保存一个post id的数组,其中的帖子受密码保护 . 然后在自定义查询中,我只是将此数组作为 post__not_in 选项的一部分传递,例如

    $query = new WP_Query(array(
        'post_type' => 'my_custom_post_type',
        'post__not_in' => get_option('__protected_posts'),
    ));
    

    这样,我可以从存档页面中排除受保护的帖子,但仍允许用户登陆受密码保护的页面以输入密码 .

  • 1

    除了@Peter Chester的回答:

    您可能还想从 Previous PostNext Post 链接中排除受密码保护的帖子,如果您在帖子页面的底部有这些帖子 .

    为此,您可以将排除项添加到 get_previous_post_whereget_next_post_where 钩子中 .

    add_filter( 'get_previous_post_where', 'my_theme_mod_adjacent' );
    add_filter( 'get_next_post_where', 'my_theme_mod_adjacent' );
    function my_theme_mod_adjacent( $where ) {
        return $where . " AND p.post_password = ''";
    }
    

相关问题