This website uses cookies to personalize your experience. By using this website you agree to our cookie policy.

Reply To: Results suggestions – how to add more than post tile in the results

Home Forums Product Support Forums Ajax Search Pro for WordPress Support Results suggestions – how to add more than post tile in the results Reply To: Results suggestions – how to add more than post tile in the results

#44443
eli-leads-maniaeli-leads-mania
Participant

Hello Ernest,

I’m currently trying to modify the search results of the Ajax Search Pro plugin to display a custom sorted list of suggested keywords from a JSON file in my theme directory. Specifically, I want the results to be sorted by relevance to the search query, similar to Google’s search suggestions.

I’ve attempted to use the ‘asp_results’ filter to achieve this, with a function that reads the JSON file, creates a new stdClass object for each keyword, and appends it to the $results array. I’m using the levenshtein() and strpos() functions to calculate a relevance score for each keyword and sort the results accordingly.

However, I’ve encountered a couple of issues:
1. The keywords from my JSON file are being displayed, but the sorting does not seem to reflect the search query. They appear to be in a preset order that does not change.
2. When I modify the function to filter the results based on the search query before returning them, no results are displayed at all.

I suspect there might be something internal to the plugin that is affecting the results. Would you be able to provide some guidance on how to correctly implement this functionality?

Here is the code I am currently using:

add_filter( ‘asp_results’, ‘asp_custom_keyword_results’, 10, 4 );
function asp_custom_keyword_results( $results, $search_id, $is_ajax, $args ) {
if ($search_id != 1) {
return $results;
}

$search_term = $args[‘_ajax_search’];

$json_file = get_theme_file_path( ‘/data/keywords.json’ );

if (file_exists($json_file)) {
$json_data = file_get_contents($json_file);
$keywords = json_decode($json_data, true);

$scores = [];

foreach($keywords as $keyword) {
$levenshtein_score = levenshtein(strtolower($search_term), strtolower($keyword));
$strpos_score = strpos(strtolower($keyword), strtolower($search_term));

$result = new stdClass();
$result->id = null;
$result->title = $keyword;
$result->content = null;
$result->image = null;
$result->post_type = null;
$result->content_type = ‘keyword’;
$result->link = “/search?keyword=” . urlencode($keyword);

$scores[] = [$strpos_score !== false ? $strpos_score : INF, $levenshtein_score];

$results[] = $result;
}

array_multisort($scores, $results);
}

return $results;
}

I appreciate your help.

Everything else works. The keywords are passing the correct parameters that we can use to perform the search. The only thing thats left is to make the results seem more intuitive.