Created
September 17, 2024 15:20
-
-
Save taricco/cc5ee4aaa5ff94830798590cedee5fc1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Exclude Custom Post Types from WordPress search | |
| function wsv_exclude_cpt_from_search( $query ) { | |
| if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) { | |
| // Exclude both 'pp_video_block' and 'sponsors-cpt' from search results | |
| $excluded_post_types = array( 'pp_video_block', 'sponsors-cpt', 'page-archive', 'impact-update-cpt', 'lp' ); | |
| $post_types = $query->get( 'post_type' ); | |
| // If $post_types is empty or set to 'any', exclude the specified post types | |
| if ( empty( $post_types ) || 'any' === $post_types ) { | |
| $post_types = get_post_types( array( 'exclude_from_search' => false ) ); | |
| foreach ( $excluded_post_types as $excluded_post_type ) { | |
| unset( $post_types[ $excluded_post_type ] ); | |
| } | |
| } elseif ( is_array( $post_types ) ) { | |
| // If post types are set, make sure excluded post types are removed | |
| $post_types = array_diff( $post_types, $excluded_post_types ); | |
| } | |
| $query->set( 'post_type', $post_types ); | |
| } | |
| } | |
| add_action( 'pre_get_posts', 'wsv_exclude_cpt_from_search' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment