Correct PHP syntax to pass values to HTTP meta refresh?

The context where I intend to use a meta refresh does not require me to be concerned with the back button, security, crawlers, response codes nor any best practices that generally recommend not using HTTP meta refresh. I do not want to use client-side script.

Note this is WordPress. The incorrect results suggest I do not have the correct PHP syntax and that is the question I am asking: what is the correct syntax to enable the following meta refresh to function as expected…

Read More
<?php
$scrnD_refresh_duration = 2;
$scrnD_refresh_url = 'http://wordpress.org';

add_action('wp_head', 'scrnD_add_meta_refresh');
function scrnD_add_meta_refresh() {
    echo '<meta http-equiv="refresh" content="'. $scrnD_refresh_duration .'; url='. $scrnD_refresh_url .'">';
}
?>

// echo displays the values as expected…

echo $scrnD_refresh_duration; // displays 2
echo $scrnD_refresh_url;      // displays http://wordpress.org

// Hardcoded values refresh as expected…

echo '<meta http-equiv="refresh" content="2; url=http://wordpress.org">';

// View source shows the function generates this with no values…

<meta http-equiv="refresh" content="; url=">

What’s the correct syntax to be used in the function?

Related posts

2 comments

  1. A function in PHP has its own “scope”, meaning that it has its own set of variables that is independent of those outside of the function.

    That’s why $scrnD_refresh_duration and $scrnD_refresh_url are empty within your function: They have never been defined there. The definitions outside of the function don’t apply.

    For cases like these, PHP offers the global statement that “pulls in” variables from the global scope. Use it like this:

    function scrnD_add_meta_refresh() {
        global $scrnD_refresh_duration, $scrnD_refresh_url;
        // ...
    }
    
  2. This is an issue of variable scope. See http://php.net/manual/en/language.variables.scope.php.

    Your function is referencing locally scoped variables, $scrnD_refresh_duration and $scrnD_refresh_url that do not hve a value inside the function. You could pass in values to your function, then reference them that way.

    function scrnD_add_meta_refresh($conent, $url) {
    ...
    

Comments are closed.