phpcsswordpressgenesis

Adding a search icon to a Wordpress Search bar


I am using the following WordPress function to output a WP search form: echo get_search_form();

Resulting output on the frontend topbar:

<form class="search-form" method="get" action="http://bio-04.eproofs.ca/" role="search">
<label class="search-form-label screen-reader-text" for="searchform-1"> To search, type and hit enter.</label>
<input class="search-form-input" type="search" name="s" id="searchform-1" placeholder=" To search, type and hit enter.">
<input class="search-form-submit" type="submit" value="Search"><meta content="http://bio-04.eproofs.ca/?s={s}">
</form>

I would like to add a search icon (magnifying glass) inside the placeholder. Currently I have text only inside the placeholder. I tried using the before pseudo element with no luck. Similar to:

label:before {
  content: "";
  position: absolute;
  left: 10px;
  top: 0;
  bottom: 0;
  width: 20px;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='25' height='25' viewBox='0 0 25 25' fill-rule='evenodd'%3E%3Cpath d='M16.036 18.455l2.404-2.405 5.586 5.587-2.404 2.404zM8.5 2C12.1 2 15 4.9 15 8.5S12.1 15 8.5 15 2 12.1 2 8.5 4.9 2 8.5 2zm0-2C3.8 0 0 3.8 0 8.5S3.8 17 8.5 17 17 13.2 17 8.5 13.2 0 8.5 0zM15 16a1 1 0 1 1 2 0 1 1 0 1 1-2 0'%3E%3C/path%3E%3C/svg%3E") center / contain no-repeat;
}

The website can be found here: http://bio-04.eproofs.ca/

Is it possible to do it just using css and the outputted existing classes ?


Solution

  • The label has some properties (probably intentionally by design or due to framework) that prevents your icon from showing up:

    If you disable these on the label (disable from another class that also add these), you will see your icon. But you will also the the text on the label, which you don't want to see.

    This is my suggestion, you place your pseudo code on the form tag instead of the label.

    form.search-form:before {
          content: "";
          position: absolute;
          left: 10px;
          top: 0;
          bottom: 0;
          width: 20px;
          background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='25' height='25' viewBox='0 0 25 25' fill-rule='evenodd'%3E%3Cpath d='M16.036 18.455l2.404-2.405 5.586 5.587-2.404 2.404zM8.5 2C12.1 2 15 4.9 15 8.5S12.1 15 8.5 15 2 12.1 2 8.5 4.9 2 8.5 2zm0-2C3.8 0 0 3.8 0 8.5S3.8 17 8.5 17 17 13.2 17 8.5 13.2 0 8.5 0zM15 16a1 1 0 1 1 2 0 1 1 0 1 1-2 0'%3E%3C/path%3E%3C/svg%3E") center / contain no-repeat;
        }
    

    Also add the following, so the icon stays in your form

    form.search-form {
      position:relative;
    }
    

    From there on you can decide to place the icon to the right of the search box instead of 10px from the left. If you don't want the search words to overlap with the search icon, you can add padding to the right of the input tag.