Home / Archive / MemberPress: Hide Protected Posts from Search Results
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: Hide Protected Posts from Search Results

Hide any posts that the current user (or guest) does not have access to from search results.

Code Preview
php
<?php
function mepr_exclude_protected_posts_from_search( $query ) {
  if( !$query->is_admin && $query->is_search && $query->is_main_query() ) {
    $posts_to_exclude = array();
    $posts = get_posts( array(
      'post_type' => get_post_types(),
      'numberposts' => -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_search' );

Comments

Add a Comment

  1. This will result in a memory error as it’ll get called recursively. You’re using `get_posts`which again will call `pre_get_posts`.

    You’ll have to use `remove_action( ‘pre_get_posts’, __FUNCTION__ );` inside your callback to prevent this.