Skip to content

Commit

Permalink
exclude 404 page from search (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
Willemijnr authored Mar 16, 2021
1 parent 072fc98 commit 04d4f21
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions clarkson-404.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

use Clarkson_Core\Objects;
use WP_Post;
use WP_Query;

class FourOFour {

Expand All @@ -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 ) {
Expand Down Expand Up @@ -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() {
Expand Down

0 comments on commit 04d4f21

Please sign in to comment.