Skip to content

Indexing content for a different domain

Kyle Benk edited this page Jan 23, 2019 · 2 revisions

SearchPress uses the site_url field to organize indexes, so that two environments can use the same ES endpoint without conflict. Sometimes, you may not want to store the index by domain, or you may want to store the index for a domain different from the current one, like when you're preparing for launch and the production environment's pre-launch domain doesn't match the post-launch domain.

Changing the index name in SearchPress couldn't be much easer, simply set SP_API()->index to whatever you want. Be careful with this that all environments don't use the same index. In this example, we'll hook into the after_setup_theme action to ensure that everything exists for this, and we'll use a fictitious function that we'll assume returns the current environment, like 'production' or 'staging':

add_action( 'after_setup_theme', function() {
	if ( class_exists( 'SP_API' ) ) {
		SP_API()->index = my_get_environment();
	}
} );

Domains in indexed permalinks

When SearchPress indexes posts, it includes permalinks. If you're using a temporary domain, those permalinks are going to be wrong when the content is indexed in Elasticsearch. This is a trickier problem than the last problem, but one solution is to replace the domain in the SP_Post object prior to indexing. SearchPress provides a filter to modify the data before it gets indexed:

add_filter( 'sp_post_pre_index', function( $post_data ) {
	$post_data['permalink'] = str_replace(
		'old.domain.com',
		'new-domain.com',
		$post_data['permalink']
	);
} );

You can do this across all fields, like post_content and post_excerpt. Be aware that the post_meta field is a bit tricker, because the data is stored in various sub-objects and the value and raw data may contain serialized PHP (and if they do, a simple search-and-replace could render that data unable to be unserialized).