Basic form in Wordpress template

I need to simply get a search term from a form into a variable. I have set up a basic form within a template file, that template file is then linked to a page within Wordpress admin. The problem I am getting is that the form doesn't submit so I am unable to use the variable. If I remove get_header(); from the template then the form will submit but obviously it break wordpress stuff.

Here is my form:

<form action="<?php the_permalink(); ?>" method="post" autocomplete="off" >
    
      <label>
        <input placeholder="Search…" name="qcsearch" type="text">
      </label>  

      <input type="submit" name="submit" value="Submit">

  </ul>
</form>

I have tried leaving out the action, using the template name which is qccerts.php and using $_SERVER['PHP_SELF']

Here is then what I am trying to do with the output:

if(isset($_POST['submit'])){   
  $searchterm = $_POST["qcsearch"];
}else{
  $searchterm = '';
}

Its basically a simple search which tells the users if there is a file by the name they search. So I need to populate $searchterm so I can use it later down the page.

Any help appreciated.

1 answer

  • answered 2021-06-18 12:44 Lajos Arpad

    It's difficult to determine what your exact problem is without a reproducible scenario. For example, without seeing your problem, I'm not sure whether the form is really not submitted at all, or submitted, but you did not see it being executed, or there is some Javascript which prevents your form from submitting. There is a possibility that the form is submitted to the wrong action as well.

    However, if you intend to keep your search term accross the pages, you could add it into session. Let's imagine these functions:

    function storeSearchTerm($searchTerm) {
        $_SESSION["searchterm"] = $searchTerm;
    }
    
    function getSearchTerm() {
        return isset($_SESSION["searchterm"]) ? $_SESSION["searchterm"] : "";
    }
    

    By calling these functions you can manage the search term, initializing it via storeSearchTerm($_POST["qcsearch"]) or something.

    As about your actual form, if it does not work, then you can submit the form in Javascript, such as

    document.getElementById("myForm").submit();
    

    and make sure that this is triggered either via an onclick attribute, or a click event listener on the button created via addEventListener.