How To Add A Custom Class To Astra Search Form

A friend had a question on how to add a custom class to the header search box in Astra that was too complex to answer in a Facebook post, so I'll put it here.

Essentially, he wanted to add a class to the input field which already has the class "search-field".

Code for Astra search form with class equals search field circled

The class he wanted to add is "addsearch".

The simplest way to do this non-destructively with PHP is to add the following code to your child theme:

add_filter ('astra_get_search_form', 'add_custom_search_class');
function add_custom_search_class($form) {
  $class_position = strpos($form, 'search-field');

  return substr_replace($form, 'addsearch ', $class_position, 0);
}

This filter pulls in the html of the form as a string.

It then looks through the html for the phrase "search-field" and returns the position of where it's located in the string.

Finally, it puts "addsearch " before "search-field" and returns the html of the form.

The space at the end of "addsearch " is intentional, so that we end up with class="addsearch search-field" as you can see below.

Code for Astra search form with class equals addsearch search field circled

Leave a Comment