Exclude password protected posts from wordpress page

Can anyone explain how I can change the below code to exclude posts that are password protected? I know I can do so with an if statement within the while statement but I want to exclude them from the WP_Query point.

$pq = new WP_Query(array('post_type' => $ptype, 'showposts' => $pshow ));

Related posts

Leave a Reply

1 comment

  1. You can make it happen with a post_where filter, just before you execute your query:

    function getNonPasswordedPosts(){    
        // Add the filter to exclude passworded posts
        add_filter('posts_where', 'excludePassworded');
    
        // Query for the posts
        $pq = new WP_Query(array('post_type' => $ptype, 'showposts' => $pshow ));
    
        // Remove the filter so that other WP queries don't exclude passworded posts
        remove_filter('posts_where', 'excludePassworded');
    
        // iterate over returned posts and do fancy stuff    
    }
    
    function excludePassworded($where) {
        $where .= " AND post_password = '' ";
        return $where;
    }