Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active Oct 16, 2020
Embed
What would you like to do?
Use Elementor to power SearchWP Supplemental Engine
<?php
// @link https://searchwp.com/v3/docs/kb/using-elementor-for-supplemental-engines/
// We need to flag the search form.
add_action( 'elementor_pro/search_form/after_input', function( $form ) {
// Check to see if this is the right Search Form.
$settings = $form->get_data( 'settings' );
if ( isset( $settings['_element_id'] ) && 'searchwp-supplemental-form' == $settings['_element_id'] ) {
?>
<input type="hidden" name="searchwp" value="supplemental" />
<?php
}
} );
// Redirect when applicable.
add_action( 'template_redirect', function() {
if ( is_search() && ! empty( $_GET['searchwp'] ) && 'supplemental' === $_GET['searchwp'] ) {
wp_safe_redirect( add_query_arg( array(
'swpquery' => get_search_query(),
), get_permalink( 18 ) ) );
exit();
}
} );
// Provide Search results.
add_filter( 'elementor/query/query_args', function( $query_vars, $widget ) {
// Check to see if this is the right Widget.
$settings = $widget->get_data( 'settings' );
if ( is_admin()
|| ! isset( $settings['posts_query_id'] )
|| ( ! empty( $settings['posts_query_id'] ) && 'searchwp-supplemental' !== $settings['posts_query_id'] ) ) {
return $query_vars;
}
// This form field was set up in Elementor.
$query = isset( $_GET['swpquery'] ) ? sanitize_text_field( $_GET['swpquery'] ) : '';
if ( ! empty( $query ) ) {
// Perform the search.
$searchwp = new SWP_Query( array(
's' => $query,
'engine' => 'supplemental', // Engine to search.
'fields' => 'ids',
'posts_per_page' => -1,
) );
if ( empty( $searchwp->posts ) ) {
$searchwp->posts = array( 0 );
}
// Override the query vars with SearchWP results.
$query_vars['post__in'] = $searchwp->posts;
$query_vars['post_type'] = 'any'; // Restricted by post__in.
$query_vars['post_status'] = 'any'; // Restricted by post__in.
$query_vars['orderby'] = 'post__in'; // Order by post__in.
$query_vars['order'] = 'DESC'; // Order descending.
} else {
// Force no results.
$query_vars['post__in'] = array( 0 );
}
return $query_vars;
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment