Skip to content

Commit 04d4f21

Browse files
authored
exclude 404 page from search (#7)
1 parent 072fc98 commit 04d4f21

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

clarkson-404.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
use Clarkson_Core\Objects;
2222
use WP_Post;
23+
use WP_Query;
2324

2425
class FourOFour {
2526

@@ -28,6 +29,7 @@ protected function __construct() {
2829
add_filter( 'clarkson_core_template_context', array( $this, 'add_404_object' ), 11 );
2930
add_action( 'the_posts', array( $this, 'set_404' ), 10, 2 );
3031
add_action( 'wp', array( $this, 'force_404' ) );
32+
add_action( 'pre_get_posts', array( $this, 'exclude_404_from_search' ) );
3133
}
3234

3335
public function set_404( $posts, $query ) {
@@ -137,6 +139,26 @@ public function field_content( $post_states, $post ) {
137139
return $post_states;
138140
}
139141

142+
/**
143+
* Exclude selected 404 page from search results
144+
*/
145+
public function exclude_404_from_search( WP_Query $query ): void {
146+
$excluded = apply_filters( 'clarkson_404_exclude_from_search', true );
147+
148+
if ( ! is_admin() && is_search() && $query->is_main_query() && $excluded ) {
149+
$id = get_option( 'clarkson-page-for-404', false );
150+
151+
if ( empty( $id ) ) {
152+
return;
153+
}
154+
155+
$excluded_posts = $query->get( 'post__not_in' ) ?: array();
156+
array_push( $excluded_posts, $id );
157+
158+
$query->set( 'post__not_in', $excluded_posts );
159+
}
160+
}
161+
140162
protected $instance = null;
141163

142164
public static function get_instance() {

0 commit comments

Comments
 (0)