隐藏来自WordPress循环的受密码保护的帖子

Geo*_*off 2 php wordpress

我在法典中找到了这个:

// Filter to hide protected posts
function exclude_protected($where) {
    global $wpdb;
    return $where .= " AND {$wpdb->posts}.post_password = '' ";
}

// Decide where to display them
function exclude_protected_action($query) {
    if( !is_single() && !is_page() && !is_admin() ) {
        add_filter( 'posts_where', 'exclude_protected' );
    }
}

// Action to queue the filter at the right time
add_action('pre_get_posts', 'exclude_protected_action');
Run Code Online (Sandbox Code Playgroud)

但这没有用。也许是因为我自定义了循环。我希望按照以下方式做一些简单的事情:

<?php $postsLatest = get_posts('numberposts=10&passwordproteced=false'); foreach($postsLatest as $post) { ?>
Run Code Online (Sandbox Code Playgroud)

那可能吗?

bir*_*ire 5

WordPress 3.9+中的has_passwordpost_password参数

你写了:

我希望按照以下方式做一些简单的事情:

passwordproteced=false
Run Code Online (Sandbox Code Playgroud)

您已经很接近了,因为可以使用boolean has_password参数:

$postsLatest = get_posts( 'has_password=false' ); 
Run Code Online (Sandbox Code Playgroud)

无需密码即可获取帖子。

您可以在的Codex中WP_Query()阅读有关此参数的更多信息,这因为get_posts只是包装器WP_Query(),并且共享输入参数。

请注意,这仅适用于WordPress 3.9+

has_password(bool)-对于带有密码的帖子为true;对于没有密码的帖子为false; 对于所有带密码和不带密码的帖子都为null(适用于3.9版)。

还有一个新的post_password参数,可能的值:

  • 空(忽略)
  • 假(仅发布没有密码的帖子)
  • true(仅带有密码的帖子)
  • 字符串(带有此确切密码的帖子)

您可以检查此Trac票

pre_get_posts在get_posts中使用过滤器:

您未成功使用pre_get_posts过滤器的原因是默认情况下会get_posts()禁止所有pre_get_posts过滤器。使用suppress_filters=false参数来应用它。