From 39a7719d702cbcb7b0dbdb0ab9c58c48c8c102f0 Mon Sep 17 00:00:00 2001 From: Adam Wood <1017872+adamwoodnz@users.noreply.github.com> Date: Fri, 2 Aug 2024 12:23:41 +1200 Subject: [PATCH] Filter searches by allowed post types if post_type is not set (#2816) Fixes https://github.com/WordPress/Learn/issues/2815 --- .../pub/wporg-learn-2024/inc/block-config.php | 3 ++- .../themes/pub/wporg-learn-2024/inc/query.php | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/wp-content/themes/pub/wporg-learn-2024/inc/block-config.php b/wp-content/themes/pub/wporg-learn-2024/inc/block-config.php index ac468856f..f40c6db12 100644 --- a/wp-content/themes/pub/wporg-learn-2024/inc/block-config.php +++ b/wp-content/themes/pub/wporg-learn-2024/inc/block-config.php @@ -54,7 +54,8 @@ function get_content_type_options( $options ) { 'lesson' => __( 'Lesson', 'wporg-learn' ), ); - $selected_slug = $wp_query->get( 'post_type' ) ? $wp_query->get( 'post_type' ) : 'any'; + $post_type = $wp_query->get( 'post_type' ); + $selected_slug = is_string( $post_type ) ? $post_type : 'any'; $label = $options[ $selected_slug ] ?? $options['any']; return array( diff --git a/wp-content/themes/pub/wporg-learn-2024/inc/query.php b/wp-content/themes/pub/wporg-learn-2024/inc/query.php index a94830297..29cdb424e 100644 --- a/wp-content/themes/pub/wporg-learn-2024/inc/query.php +++ b/wp-content/themes/pub/wporg-learn-2024/inc/query.php @@ -7,6 +7,7 @@ add_action( 'pre_get_posts', __NAMESPACE__ . '\add_language_to_archive_queries' ); add_action( 'pre_get_posts', __NAMESPACE__ . '\add_excluded_to_lesson_archive_query' ); +add_action( 'pre_get_posts', __NAMESPACE__ . '\filter_search_queries_by_post_type' ); add_filter( 'request', __NAMESPACE__ . '\handle_all_level_query' ); /** @@ -80,6 +81,23 @@ function add_excluded_to_lesson_archive_query( $query ) { } } +/** + * Filter search queries by post type. + * Only include courses and lessons in search results unless post_type is set, eg. for an archive search. + * + * @param WP_Query $query The query object. + * @return WP_Query The modified query object. + */ +function filter_search_queries_by_post_type( $query ) { + if ( ! is_admin() && $query->is_search() && $query->is_main_query() ) { + if ( ! $query->get( 'post_type' ) ) { + $query->set( 'post_type', array( 'course', 'lesson' ) ); + } + } + + return $query; +} + /** * Modify the request. *