Home / Archive / MemberPress: Exclude MemberPress Custom Post Types from WordPress Search Results
Duplicate Snippet

Embed Snippet on Your Site

MemberPress: Exclude MemberPress Custom Post Types from WordPress Search Results

By default, protected content could show up in the website search results. Though still protected, they will be listed.

This code snippet excludes specific custom post type from appearing in WordPress search results.

The sample code below excludes the MP Downloads files (the mpdl-file post type).

To exclude a different post type, replace mpdl-file with the post type you want to exclude on this line 5

Code Preview
php
<?php
function exclude_ml_file_from_search( $query ) {
  // Check if it is not an admin page, is a search query, and is the main query
  if ( !$query->is_admin && $query->is_search && $query->is_main_query() ) {
    // Exclude the 'mpdl-file' post type from the search results
    $query->set( 'post_type', array_diff( get_post_types(), array('mpdl-file') ) );
  }
}
// Hook the function to the 'pre_get_posts' action
add_action('pre_get_posts', 'exclude_mpdl_file_from_search');

Comments

Add a Comment