Posted on

Modifying the search form on the fly

I set up a short coded search box to search my Learndash e-course for one specific category only:

[ searchform ld_topic_category="156" ]

It works perfectly except one thing: if no results show, it takes you to the default WordPress page and presents you with the standard search box that no longer searches category 156.

This problem isn’t generally very hard to fix. The exact solution depends somewhat on the theme. In this case the theme used was Astra, and Astra makes this very easy by using the default WordPress search form powered by get_search_form().

We want to modify the search form. If the ld_topic_category parameter is set, the search form should include it and keep the value. That way the “No results found” page would use the same search parameter. We can’t just hardcode it, because we don’t want the search form to always use the parameter; only when the user came from the restricted search.

The search form can be modified with the get_search_form filter hook. That hook gives us the full HTML code of the form, and we can just insert the ld_topic_category filter in there as a <input type="hidden"> tag, if the parameter is set. Like this:

add_filter( 'get_search_form', 'add_ld_topic_category' );
function add_ld_topic_category( $form ) {
  if ( isset( $_GET['ld_topic_category'] ) ) {
    $value = esc_attr( $_GET['ld_topic_category'] );
    $form  = str_replace( '</form>', '<input type="hidden" name="ld_topic_category" value="' . $value . '" /></form>', $form );
  }
  return $form;
}

Add this function to your site.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *