Created
August 9, 2024 03:15
-
-
Save kmwalsh/1eda0b04c06739756a047ba4c70f4c53 to your computer and use it in GitHub Desktop.
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
/** | |
* SearchWP relevant customization. | |
* | |
* @package lnct | |
*/ | |
class LNCT_SearchWP { | |
public function __construct() { | |
add_filter( 'searchwp_live_search_query_args', [ $this, 'restrict_searchwp_post_types'] ); | |
add_action( 'template_redirect', [ $this, 'override_searchwp_query_for_specific_page_paths' ] ); | |
} | |
/** | |
* Get the page path to determine which page a SearchWP form is | |
* embedded upon. | |
* | |
* @return string The last part of the page path. | |
*/ | |
public function get_searchwp_form_path() { | |
return preg_replace('#/+#','', parse_url( wp_get_referer(), PHP_URL_PATH ) ); | |
} | |
/** | |
* SearchWP Ajax Live Search doesn't seem to have a way to send users | |
* to a specific URL on search, they all go to the main site search | |
* URL. This provides a way for a user searching on the Resources (or | |
* Blog, or Event) page to still get sent back to Resources (etc.) on a | |
* search action performed there. | |
* | |
* Used for Resource Library, News/Events, and Blog. Doesn't affect primary | |
* site search. | |
* | |
* This snippet can likely be removed/remedied by purchase of the premium | |
* SearchWP plugin & its configuration, if desired. | |
* | |
* @return void | |
*/ | |
public function override_searchwp_query_for_specific_page_paths() { | |
// only if we're on the SearchWP form ID of 1 | |
if ( isset( $_GET['swp_form']['form_id'] ) && '1' === $_GET['swp_form']['form_id'] ) : | |
// get the path and remove slashes from the referring URL | |
$path = $this->get_searchwp_form_path(); | |
// redirect back to the referring URL path | |
wp_redirect( home_url( $path ) . '?s=' . urlencode( get_query_var( 's' ) ) ); | |
exit(); | |
endif; | |
} | |
/** | |
* Restrict Live Search queries to only certain post types based on | |
* the URL where the search form is embedded. | |
* | |
* @link https://wordpress.org/support/topic/exclude-page-ids-and-post-ids/#post-17280519 | |
*/ | |
public function restrict_searchwp_post_types( $args ) { | |
switch ( $this->get_searchwp_form_path() ) { | |
case 'blog': | |
$post_types = [ 'post' ]; | |
break; | |
case 'news-events': | |
$post_types = [ 'lnct_updates', 'lnct_event' ]; | |
break; | |
default: | |
$post_types = [ 'post', 'lnct_updates', 'lnct_event', 'lnct_resource' ]; | |
break; | |
} | |
$args['post_type'] = $post_types; | |
return $args; | |
} | |
} | |
new LNCT_SearchWP; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment