get WordPress variable from external php file does not work

I have two variables in an external file

function.php

Read More
$bottomID   =  get_post_meta($post->ID, "bottom", true);

$xstring    =  "This is a string"; 

now if I echo them from my index.php

echo $bottomID;
echo $xstring;

I only get the value from $xstring but not from $bottomID

I know that $bottomID works since if I have it in the index.php file it echo out a value.

Cant figure out whats the problem

Any ideas?

Related posts

Leave a Reply

2 comments

  1. If you set a variable in function.php it is in the global scope, variable will be visible in index.php only because they are loaded in the same scope, but it is not available to all of your templates. Most templates are loaded by a function, and in PHP any variable used inside a function is by default limited to the local function scope, so you must explicit define a variable as global.

    In your case, variable is set and the value is false ( test with: var_dump( isset( $bottomID ) ); in index.php ), that’s because you use a global $post, that not yet exists, as parameter in the get_post_meta() function, so the return value of that function is false.

  2. I would write a function in functions.php and call it in index.php.

    function get_id_xstring()
    {
        global $post;
        $return = array(
            'id'      => get_post_meta( $post->ID, 'bottom', true ),
            'xstring' => 'This is a string';
        );
        return $return;
    }
    

    And in index.php:

    $my_vars = get_id_xstring();
    echo $my_vars['id']; // bottomID
    echo $my_vars['xstring'];