PHP, $_GET[“variable “] only works if with certain values

I can’t get my head round this. The code below works fine at getting the variable “s” from the url and displaying the h1 but I’ve found it only works is the variable is set as certain characters. It works if the variable is set as either “l”, “m” or “n”. But it doesn’t work in most cases including if the variable is set as “w”, “wind”, “nn” or even a random collection of letter like “sfda”.

if ($_GET["s"]=='l'){?>
    <h1>Services for Companies</h1><?php
}

When it isn’t working, WordPress displays a “Sorry, that page can’t be found” page.

Related posts

Leave a Reply

3 comments

  1. If you just want to check if a variable exists, you can use isset:

    if( isset( $_GET['s'] ) ) {
        echo 'Yes, this variable exists.';
    }
    

    But in WordPress you should use the get_query_var() function to access query parameters. This function has some basic security checks included.

    if( get_query_var( 's' ) ) {
        echo 'Yes, this variable exists.';
    }
    

    Be aware that there are multiple GET variables, that are already used in WordPress. For a full list see “WordPress Query Vars”.

    See also: How to pass extra variables in URL with WordPress

  2. you can try :

    GET and POST method

    if(isset($_REQUEST['s'])){
    echo 's ='.$_REQUEST['s'];
    }
    

    or only get method

    if(isset($_GET['s'])){
    echo 's='.$_GET['s'];
    }
    
  3. WordPress uses query variables to perform certain functions. In this case, s is the normal WordPress search query. I would recommend using a very specific url query, like headerquery or titlequery to avoid any conflicts.