Home / Archive / MemberPress: ACF – Exclude Protected Posts From ACF Repeater Field
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: ACF – Exclude Protected Posts From ACF Repeater Field

The code snippet ensures that protected MemberPress posts are excluded from custom queries used in Advanced Custom Fields (ACF) repeater fields. This prevents these posts from being displayed to unauthorized users.

To exclude protected posts based on the specific post type, modify the get_posts array to include the specific post type.

The get_post_types() should be replaced by the required post type, on this line:

'post_type' => get_post_types(),

For example, to exclude all posts with the custom post type called events, the mentioned line of the code would look like this:

'post_type' => 'events',

Code Preview
php
<?php
function exclude_protected_memberpress_posts( $query ) {
    // Ensure we are not in the admin area and it's the main query
    if ( ! is_admin() && $query->is_main_query() ) {
        // Check if we are on the repeater field context
        if ( function_exists( 'get_field' ) && get_field( 'your_repeater_field_name' ) ) {
            $posts_to_exclude = array();
            // Get all posts
            $posts = get_posts( array(
                'post_type'   => get_post_types(),
                'post_status' => 'publish',
                'numberposts' => -1
            ) );
            // Loop through each post and check if it's protected
            foreach ( $posts as $post ) {
                if ( MeprRule::is_locked( $post ) ) {
                    $posts_to_exclude[] = $post->ID;
                }
            }
            // Exclude protected posts from the query
            if ( ! empty( $posts_to_exclude ) ) {
                $query->set( 'post__not_in', $posts_to_exclude );
            }
        }
    }
}
// Attach the 'exclude_protected_memberpress_posts' function to the 'pre_get_posts' action.
add_action( 'pre_get_posts', 'exclude_protected_memberpress_posts' );

Comments

Add a Comment