Knowledge Base

Custom fields in result titles

in Ajax Search Pro Tips Tags: ajax search proasp_resultscustom fieldsfiltertutorial

The asp_results filter can be used to add custom fields to titles of the results. Use these custom filter examples in the functions.php file in your current theme directory.

A basic usage example:

// Adds the custom_field value to the title separated by a space.
add_filter( 'asp_results', 'asp_custom_field_to_title', 1, 1 );
 
function asp_custom_field_to_title( $results ) {
  $custom_field = "custom_field";

  foreach ($results as $k=>$v) {
    if ($v->content_type != "pagepost") continue;
    $meta_value = get_post_meta($v->id, $custom_field, true);
    // Modify the post title to add the meta value
    if ( !empty($meta_value) )
      $results[$k]->title  .= " " . $meta_value;
  }
 
  return $results;
}

WooCommerce example for price field

WooCommerce example, to add the _price field to product custom post types only:

add_filter( 'asp_results', 'asp_price_field_to_title', 1, 1 );
 
function asp_price_field_to_title( $results ) {
  $custom_field = "_price";

  foreach ($results as $k=>$v) {
    if ($v->content_type != "pagepost" || $v->post_type != "product")
      continue;
    $meta_value = get_post_meta($v->id, $custom_field, true);
    // Modify the post title to add the meta value
    if ( !empty($meta_value) )
      $results[$k]->title  .= " - " . $meta_value . "$";
  }
 
  return $results;
}