Knowledge Base

Custom fields and values in result titles or contents

in Ajax Search Pro Tips Tags: ajax search proasp_resultscustom fieldsfiltertutorial

In newer plugin versions (4.14.x and further) there is a possibility to use the advanced title and content fields to display custom fields content within the result titles or content, without custom coding.

For more specific purposes, 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:

add_filter( 'asp_results', 'asp_custom_field_to_results', 10, 1 ); 
function asp_custom_field_to_results( $results ) {
  $custom_field = 'custom_field'; // Enter the custom field name
  $field = 'title';               // 'title' or 'content'
  $position = 'before';           // 'before' or 'after'
  $delimiter = ' ';               // character between the field value and the field

  foreach ($results as $k=>&$r) {
    if ($r->content_type != 'pagepost') continue;
    if ( function_exists('get_field') )
        $meta_value = get_field( $r->id, $custom_field, true ); // ACF support
    else
        $meta_value = get_post_meta( $r->id, $custom_field, true );
    // Modify the post title to add the meta value
    if ( !empty($meta_value) ) {
      if ( $field == 'title' ) {
        if ( $position == 'before' )
          $r->title  = $meta_value . $delimiter . $r->title;
        else
          $r->title  .= $delimiter . $meta_value;
      } else {
        if ( $position == 'before' )
          $r->content  = $meta_value . $delimiter . $r->content;
        else
          $r->content  .= $delimiter . $meta_value;
      }
    }
  }
 
  return $results;
}

Related: WooCommerce – Get formatted price in result title or in content