Skip to content
Matthew Boynes edited this page Apr 19, 2020 · 3 revisions

SearchPress' default indexing is very powerful and flexible and should cover most, if not all, of your needs. If you happen upon a circumstance where you need to add data to a post, SearchPress has a lot of flexibility to help you do what you need. Let's walk through an example to illustrate how you would customize the data that gets indexed in Elasticsearch.

Store Search (1 of 3)

Let's say you make or sell products and you want to make a search page on your site where people can enter their address and find the closest stores where they can find your products. Elasticsearch makes this otherwise-complex task very simple, but SearchPress doesn't surface any geolocation data out-of-the-box (since there is none in WordPress by default).

When we index our content, we need to set the geolocation coordinates in their own field. To do so, we'll leverage the sp_post_pre_index action to add the geolocation data. This is the most common hook you would use to manipulate post data stored in Elasticsearch.

add_filter(
	'sp_post_pre_index',
	function( $post_data ) {
		// If this isn't a `store` post type, save some effort and return early.
		if ( 'store' !== $post_data['post_type'] ) {
			return $post_data;
		}

		// In this case, the lat and long are stored in individual post meta.
		$latitude  = get_post_meta( $post_data['post_id'], 'latitude', true );
		$longitude = get_post_meta( $post_data['post_id'], 'longitude', true );

		// Only proceed if each is a numeric value.
		if ( is_numeric( $latitude ) && is_numeric( $longitude ) ) {
			// There are 4 ways to pass geo point data to Elasticsearch.
			// This is the object syntax, `{"lat": x, "lon": y}`.
			// {@see https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-point.html}
			$post_data['location'] = [
				'lat' => (float) $latitude,
				'lon' => (float) $longitude,
			];
		}

		return $post_data;
	}
);

Now, before a post is converted to JSON and indexed in Elasticsearch, its geolocation data will be added. Part 2 of this example will be adding that field to the mapping in Custom Mapping, and part 3 will be creating the search in Store Search.