Count the number of times the search form template gets included on a page

Just few simple ideas:

A) Here’s one suggestion using the get_search_form filter with a static variable to handle the instance counting:

add_filter( 'get_search_form', function( $form )
{
    static $instance = 0;
    $instance++;

    // Setup your form here with the $instance variable as needed:
    $form = '<form>...</form>';

    return $form;
} );

B) Another workaround would be to add

$instance = apply_filters( 'wpse_search_instance', 0 );

to your searchform.php file, where you add the following to your functions.php file:

add_filter( 'wpse_search_instance', function( $count )
{
    static $instance = 0;
    return ++$instance; 
} );

but then again this kind of instance counting could be modified through another filter callback 😉

C) Then we could also do it like this within your searchform.php file:

do_action( 'wpse_search_instance' );

$instance = did_action( 'wpse_search_instance' );

to handle the instance counting. This assumes you don’t fire up the wpse_search_counting action elsewhere.

D) We can find the following hook inside the get_search_form() function:

 do_action( 'pre_get_search_form' );

so we would only need to call:

$instance = did_action( 'pre_get_search_form' );

within the searchform.php. I think this is the easiest workaround so far.

tech