Home / Archive / MemberPress: Exclude Protected Posts From the Main Query
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: Exclude Protected Posts From the Main Query

This code snippet modifies the main WordPress query to exclude all posts related to the specified post type, if they are protected by MemberPress rules. Accordingly, these posts won’t be displayed on archive pages like the blog or category page.

The sample code will exclude all protected posts ('post_type' => 'post').

The code can be applied to other post types (e.g., pages, custom post types, etc.) by replacing post with the needed post type, on these lines:

$posts = get_posts(array('post_type' => 'post', 'posts_per_page' => -1));

The code can be applied to multiple post types by replacing post with the array of different post types (e.g. array('post_type_1', 'post_type_2')) on the lines mentioned above. For example, to apply the code snippet to both posts and pages, the mentioned code lines would look like this:

$posts = get_posts(array('post_type' => array('post', 'page'), 'posts_per_page' => -1));

Code Preview
php
<?php
function mepr_exclude_protected_posts_from_query_block( $query ) {
    if (! is_admin() && $query->is_main_query()) {
        $posts_to_exclude = array();
        $posts = get_posts(array('post_type' => 'post', 'posts_per_page' => -1));
        foreach ($posts as $post) {
            if (MeprRule::is_locked($post)) {
                $posts_to_exclude[] = $post->ID;
            }
        }
        if (! empty($posts_to_exclude)) {
            $query->set('post__not_in', $posts_to_exclude);
        }
    }
}
add_action( 'pre_get_posts', 'mepr_exclude_protected_posts_from_query_block' );

Comments

Add a Comment