From 04d4f21e0a1307332877c7b0db5510e03cd88c2e Mon Sep 17 00:00:00 2001 From: Willemijn Date: Tue, 16 Mar 2021 15:22:50 +0100 Subject: [PATCH] exclude 404 page from search (#7) --- clarkson-404.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/clarkson-404.php b/clarkson-404.php index 49e2e3e..1df5bb1 100644 --- a/clarkson-404.php +++ b/clarkson-404.php @@ -20,6 +20,7 @@ use Clarkson_Core\Objects; use WP_Post; +use WP_Query; class FourOFour { @@ -28,6 +29,7 @@ protected function __construct() { add_filter( 'clarkson_core_template_context', array( $this, 'add_404_object' ), 11 ); add_action( 'the_posts', array( $this, 'set_404' ), 10, 2 ); add_action( 'wp', array( $this, 'force_404' ) ); + add_action( 'pre_get_posts', array( $this, 'exclude_404_from_search' ) ); } public function set_404( $posts, $query ) { @@ -137,6 +139,26 @@ public function field_content( $post_states, $post ) { return $post_states; } + /** + * Exclude selected 404 page from search results + */ + public function exclude_404_from_search( WP_Query $query ): void { + $excluded = apply_filters( 'clarkson_404_exclude_from_search', true ); + + if ( ! is_admin() && is_search() && $query->is_main_query() && $excluded ) { + $id = get_option( 'clarkson-page-for-404', false ); + + if ( empty( $id ) ) { + return; + } + + $excluded_posts = $query->get( 'post__not_in' ) ?: array(); + array_push( $excluded_posts, $id ); + + $query->set( 'post__not_in', $excluded_posts ); + } + } + protected $instance = null; public static function get_instance() {