Knowledge Base

WooCommerce: Get formatted price in result title or in content

Solution 1: Advanced fields on the back-end

The plugin allows displaying custom field contents within results, however it's only a simple content to display feature, there is no further processing executed.

Solution 2: Custom code

For a better, more efficient solution, a small custom code snippet is required. This will make sure to output the price for items that have one, using the proper formatting.

Price after the title

Use this custom filter in the functions.php file in your active theme directory:

add_filter('asp_results', 'asp_add_price_to_title_if_exists', 10, 1);
function asp_add_price_to_title_if_exists($results) {
  if ( !function_exists('wc_get_product') ) return $results;
  
  foreach ($results as $k => &$r) {
    if ( !isset($r->post_type) || 
         !in_array($r->post_type, array('product', 'product_variation')) )
         continue;
    $p = wc_get_product($r->id);
    $r->title .= ' '.wc_price($p->get_price());
  }
  
  return $results;
}
Price before the content

Use this custom filter in the functions.php file in your active theme directory:

add_filter('asp_results', 'asp_add_price_to_desc_if_exists', 10, 1);
function asp_add_price_to_desc_if_exists($results) {
  if ( !function_exists('wc_get_product') ) return $results;
  
  foreach ($results as $k => &$r) {
    if ( !isset($r->post_type) || 
         !in_array($r->post_type, array('product', 'product_variation')) )
         continue;
    $p = wc_get_product($r->id);
    $r->content = wc_price($p->get_price()) .' '. $r->content;
  }
  
  return $results;
}