0

I need to disable our site's gated content from showing up in search results. Currently, I'm using the following code to exclude pages by post ID:

// Exclude gated content (download pages) from site search

function mm_search_filter( $query ) {
  if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
    $query->set( 'post__not_in', array( 18321, 17218, 17212, 17217, 17136, 16269, 17484, 7349, 9264, 15919, 15920, 15921, 15922, 7939, 15930, 16700, 8923, 15820, 18489, 18234, 15970, 18235, 18236, 16065 ) );
  }
}
add_action( 'pre_get_posts', 'mm_search_filter' );

This seems a little clunky though and as our gated content pages grow, so will this list. So my question is, is there a way to do the same thing by excluding page titles that start with a certain string value? To further clarify my situation, all of the pages i'm currently excluding have page titles that start with 'download-' :

  • download-marketing-roadmap
  • download-social-media-field-guide
  • download-big-book-of-working-smarter
  • etc, etc, etc....

Would greatly appreciate a solution to this!

3

You can query a list of post IDs using $wpdb based on their slugs, and then use that in your filter. Here's a simple example of how to do this:

function mm_search_filter( $query ) {

    // We will query a list of post IDs 
    // by using $wpdb
    global $wpdb;
    $post_ids = $wpdb->get_results("SELECT ID FROM wp_posts WHERE post_name IN 'download-'");

    // Now, pass the array of post IDs in
    if ( 
        ! $query->is_admin && 
        $query->is_search && 
        $query->is_main_query() && 
        ! empty ( $post_ids )
    ) {
        $query->set( 'post__not_in', $post_ids );
    }
}
add_action( 'pre_get_posts', 'mm_search_filter' );
1
  • Thank you Jack! This is very useful to know. Appreciate the quick response!
    – McDeeez
    Mar 14 '18 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.