Knowledge Base

How to change the results URL to something else?

in Ajax Search Pro Tips Tags: changecustom urldifferent urlmetaurl

Similarly as in other examples, the 'asp_results' filter is the key to access each result after post-processing for manipulating their data.

You can use this basic filter function in your themes functions.php file to access the post title, and make modifications to it (this example will simply change every result link to google):

add_filter( 'asp_results', 'asp_custom_link_results', 1, 1 );

function asp_custom_link_results( $results ) {

  // Parse through each result item
  foreach ($results as $k=>$v) {
    /**
     * In this context the
     *      $results[$k]->link
     * variable holds the result link. Make modifications to that variable.
     */
    $results[$k]->link  = 'https://google.com';
  }

  return $results;
}
Parsing the url from post meta

A more practical example is if the desired url is stored in the post meta. The following example will take change the result url to the one stored under the “custom_url” post meta key. Change the $key variable in the code if you use different post meta:

add_filter( 'asp_results', 'asp_custom_link_meta_results', 1, 1 );
function asp_custom_link_meta_results( $results ) {

  // Change this variable to whatever meta key you are using
  $key = 'custom_url';

  // Parse through each result item
  foreach ($results as $k=>$v) {
    if ( function_exists('get_field') )
        $new_url = get_field( $v->id, $key, true ); // ACF support
    else
        $new_url = get_post_meta( $v->id, $key, true );

    // Change only, if the meta is specified
    if ($new_url != '')
      $results[$k]->link  = $new_url;
  }

  return $results;
}