Last active
January 6, 2022 11:22
-
-
Save tamara-m/6b8bdb61aa9cf9b2a59a63ffa9e0d4f7 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
/** | |
* Load Elasticseach PHP 7 Client via composer | |
* Updated for ElasticPress 3.3 | |
*/ | |
require 'vendor/autoload.php'; | |
/** | |
* Init Elasticsearch PHP Client | |
*/ | |
use Elasticsearch\ClientBuilder; | |
use ElasticPress\Indexables as Indexables; | |
use ElasticPress\Utils; | |
/** | |
* Register Elasticpress Autosuggest Endpoint | |
* | |
* This is the endpoint you have to specify in the admin | |
* like this: http(s)://domain.com/wp-json/elasticpress/autosuggest/ | |
*/ | |
add_action( 'rest_api_init', function() { | |
register_rest_route( 'elasticpress', '/autosuggest/', [ | |
'methods' => \WP_REST_Server::CREATABLE, | |
'callback' => 'ep_autosuggest', | |
] ); | |
} ); | |
/** | |
* Elasticpress Autosuggest Endpoint Callback | |
* | |
* gets host and index name dynamically. Otherwise, | |
* if not specified, host would default to localhost:9200 | |
* and index name would default to 'index' | |
* | |
* @param \WP_REST_Request $data | |
* @return array|callable | |
*/ | |
function ep_autosuggest( \WP_REST_Request $data ){ | |
$client = ClientBuilder::create(); | |
$client->setHosts( [ElasticPress\Utils\get_host()] ); // get host dynamically | |
$client = $client->build(); | |
$json_params = $data->get_json_params(); | |
$params = [ | |
'index' => Indexables::factory()->get( 'post' )->get_index_name(), // get index dynamically | |
'body' => $json_params | |
]; | |
$response = $client->search( $params ); | |
return $response; | |
} | |
/* | |
* Exclude attachments from autosuggest results | |
*/ | |
function ep_autosuggest_options($epas_options){ | |
unset($epas_options['mimeTypes']); | |
$epas_options['mimeTypes'] = []; | |
return $epas_options; | |
} | |
add_filter( 'ep_autosuggest_options', 'ep_autosuggest_options', 20, 1 ); | |
function filter_term_suggest_post_status($post_status){ | |
unset($post_status); | |
$post_status = [ 'publish' ]; | |
return $post_status; | |
} | |
add_filter( 'ep_term_suggest_post_status', 'filter_term_suggest_post_status', 10, 1 ); |
@MikeLx You should turn this file into a WordPress plugin, or use it as one of the files inside a WordPress plugin. Check out this https://developer.wordpress.org/plugins/plugin-basics/header-requirements/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Where does this file go?