ElasticPress icon indicating copy to clipboard operation
ElasticPress copied to clipboard

Feature/preference filter

Open mmcachran opened this issue 6 years ago • 1 comments

Description of the Change

Allow a preference query string to be added to the search request path to ensure search results have the same sorting. This avoids duplicate results when custom sorting is used.

Benefits

Allows an easier way for a preference query string to be added to the request path.

Verification Process

Use the following example filter to ensure the unique ID is the same throughout pagination requests.

/**
 * Gets a unique string for the current user.
 *
 * @param string $null            The current user key value or null.
 * @param string $path            The current request path.
 * @param string $name            The index name.
 * @param string $type            The index type.
 * @param array  $query           Prepared ES query.
 * @param array  $query_args      WP Query args.
 * @return string                 Unique string for the user.
 */
function get_unique_user_key( $null, string $path, string $name, string $type, array $query, array $query_args ): string {
	// Bail early if the user is logged in and use their user ID.
	if ( \is_user_logged_in() ) {
		return md5( get_current_user_id() );
	}

	// Parameters for the key.
	$key_parameters = [
		'REMOTE_ADDR',
		'HTTP_CLIENT_IP',
		'HTTP_X_FORWARDED_FOR',
		'HTTP_USER_AGENT',
	];

	// Holds the unique key for the user.
	$key = '';

	// Loop through parameters to build the unique key.
	foreach ( $key_parameters as $parameter ) {
		// Get the server variable value.
		$value = filter_input( INPUT_SERVER, $parameter, FILTER_SANITIZE_ENCODED );

		// Skip if parameter isn't set.
		if ( empty( $value ) ) {
			continue;
		}

		// Add it to our unique key.
		$key .= sanitize_text_field( wp_unslash( $value ) );
	}

	// Bail early if we have a unique key.
	if ( ! empty( $key ) ) {
		return md5( $key );
	}

	// Create a session and return the ID if we haven't created a unique key.
	if ( ! session_id() ) {
		session_start();
	}

	return session_id();
}
add_filter( 'ep_preference', 'get_unique_user_key', 10, 6 );

Checklist:

  • [x] I have read the CONTRIBUTING document.
  • [x] My code follows the code style of this project.
  • [ ] My change requires a change to the documentation.
  • [ ] I have updated the documentation accordingly.
  • [ ] I have added tests to cover my change.
  • [x] All new and existing tests passed.

mmcachran avatar Oct 02 '19 02:10 mmcachran

@dustinrue can you please check if this would bring any performance penalty?

felipeelia avatar Mar 15 '22 17:03 felipeelia