Last active
February 6, 2022 11:34
-
-
Save barrd/5839fb4596180035166e78fa9ffaa4f2 to your computer and use it in GitHub Desktop.
WordPress Search Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Exclude posts by ID | |
* | |
* @param array $query The WP_Query instance. | |
*/ | |
function exclude_posts_from_search( $query ) { | |
if ( $query->is_main_query() && is_search() ) { | |
// Add post IDs into array. | |
$post_ids = array( 10, 11, 12 ); | |
$query->set( 'post__not_in', $post_ids ); | |
} | |
} | |
add_action( 'pre_get_posts', 'exclude_posts_from_search' ); | |
/** | |
* Auto-redirect when Search Query only returns one match | |
* Ensure we don't activate on the last page of results with only one entry by checking `paged` | |
*/ | |
function one_match_redirect() { | |
if ( is_search() ) { | |
global $wp_query; | |
if ( 1 === $wp_query->post_count && 0 === get_query_var( 'paged' ) ) { | |
wp_safe_redirect( get_permalink( $wp_query->posts['0']->ID ) ); | |
exit(); | |
} | |
} | |
} | |
add_action( 'template_redirect', 'one_match_redirect' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment