Skip to main contentSkip to footer

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.

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

How to display relevancy score
Relevanssi stores the relevance score it uses to sort results in the $post variable. Just add something like <?php echo…
Search results in random order
Do you want to order your search results in random order? Here’s how: add_filter( 'relevanssi_hits_filter', 'shuffle_search' ); function shuffle_search( $hits…

Related Posts:

Currently there are no related posts available.

Comment Section:

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed