Skip to content

Instantly share code, notes, and snippets.

@stephensabatini
Created November 10, 2020 00:04
Show Gist options
  • Save stephensabatini/79c0cb6753010ffa1a9157131b6c5f9e to your computer and use it in GitHub Desktop.
Save stephensabatini/79c0cb6753010ffa1a9157131b6c5f9e to your computer and use it in GitHub Desktop.
Filter by post type.
<?php
/**
* Add post type filter support for search.
*
* @param array $query
*
* @since 1.0.0
*/
public function filter_post_type( $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$filter_post_type = ! empty( $_GET[ 'filter_post_type' ] ) ? $_GET[ 'filter_post_type' ] : '';
if ( ! empty( $filter_post_type ) && post_type_exists( $filter_post_type ) ) {
$query->set( 'post_type', $filter_post_type );
}
}
return $query;
}
add_filter( 'pre_get_posts', 'filter_post_type' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment