Label issue/question


I’m having a hard time with this bit of code, which is used in a wordpress context. This snippet is called by a function where needed.

I’m in a scenario where the search form may appear more than once on a page (att he very top, at the very bottom if document must be scrolled down for a long while). And I can’t figure out how to solve the label/id issue that multiple occurences rise.

Obvious approach: do not re-use same HTML code.

But I’m sure there’s a better approach.

<form action="<?php bloginfo('url'); ?>/" method="get">
        <label for="searchform"><?php _e( 'Search for:' ); ?></label>
        <input type="text" name="s" id="searchform" value="<?php the_search_query(); ?>" />
        <input type="submit" value="<?php _e( 'Go' ); ?>" />

That would be my suggestion. The id must be unique. Otherwise, in this case, it will presumably confuse the label.

Perhaps an alternative would be to do away with for/id and nest the input inside the label. You can read about that option here.

  1. stop opening and closing PHP on every line. (If I had my way, <?php and ?> wouldn’t even EXIST in PHP)

  2. put that form in a function.

  3. pass to that function a unique identifier for each copy of the form. Form elements can use the same NAMES, they just can’t use the same ID’s.

function searchForm(uniquePrefix='') {

	echo '
		<label for="',uniquePrefix,'_searchText">
			',_e('Search for:'),'
			value="',_e( 'Go' ),'"


Guessing slightly since I have no clue if _e is a alias/wrapper to echo, or if it’s returning it’s value. If that’s a language lookup, I’d probably just use an array lookup than some function.

Send it a unique prefix for each copy you use. The ID does NOT get sent as part of the formdata, just NAME does.

EXACTLY the type of thing functions are meant to handle.


Would output two copies, one with the form being id=“top_searchForm”, with the FOR and INPUT->ID being “top_searchText” – the second being bottom_ instead of top_

One set of code, for two different copies of the same form on a page.

Did other people already tell you how you rock? 'Cause you do!