admin管理员组

文章数量:1289957

I have a script that I want to display in the wp_head, but only if a URL variable is passed. For example, if someone visits /?feedback=yes I want the following script to display:

  <script>
    alert( 'Hello, world!' );
  </script>

I can already have this display all the time via the following function, but it's the part around having it only display if that URL variable exists that I'm not sure on.

/* Describe what the code snippet does so you can remember later on */
add_action('wp_head', 'your_function_name');
function your_function_name(){
?>
  <script>
    alert( 'Hello, world!' );
  </script>
<?php
};

I have a script that I want to display in the wp_head, but only if a URL variable is passed. For example, if someone visits https://example/?feedback=yes I want the following script to display:

  <script>
    alert( 'Hello, world!' );
  </script>

I can already have this display all the time via the following function, but it's the part around having it only display if that URL variable exists that I'm not sure on.

/* Describe what the code snippet does so you can remember later on */
add_action('wp_head', 'your_function_name');
function your_function_name(){
?>
  <script>
    alert( 'Hello, world!' );
  </script>
<?php
};
Share Improve this question asked Jun 23, 2021 at 16:53 Moez TharaniMoez Tharani 1
Add a comment  | 

1 Answer 1

Reset to default 0

URL variables like that are stored in the $_GET variable. You can check the existence and value of one like this:

add_action(
    'wp_head',
    function() {
        if ( isset( $_GET['feedback'] ) && 'yes' === $_GET['feedback'] ) {
            ?>
            <script>
                alert( 'Hello, world!' );
            </script>
            <?php
        }
    }
);

The check for isset() is necessary as checking $_GET['feedback'] alone will throw an error if it's not present in the URL at all.

本文标签: functionsDisplay Script in Header When URL Variable Present