Global variable set in the template’s header.php is unable to echo in footer.php

E.g. I set this in header.php in my template:

<?php $postidextra = get_the_ID(); ?> 
<?php $sidebar_state = get_post_meta($postidextra , 'rw_sidebar_state', true); ?>

And I can echo $sidebar_state in header.php, it’s working.

Read More

However, when I try to echo this variable from footer.php or page.php it’s not working and I need to repeat my code to get the post id and post meta etc. which is repeating and a bad practice.

Why it’s not available if it is just include?

How to make the variable available in all files across WP template files?

UPDATE:

After suggestion to use global variables I am still unable to echo $sidebar_state; in footer.php. My code in header.php looks like this:

 <?php global $postidextra; ?> 
 <?php $postidextra = get_the_ID(); ?>
 <?php global $sidebar_state; ?>
 <?php $sidebar_state = get_post_meta($postidextra , 'rw_sidebar_state', true); ?>

Footer.php looks like this:

<?php
/**
 * The template for displaying the footer.
 *
 * Contains footer content and the closing of the
 * #main and #page div elements.
 *
 * @package WordPress
 * @subpackage Twenty_Twelve
 * @since Twenty Twelve 1.0
 */
?>
    </div><!-- #main .wrapper -->
    <footer id="colophon" role="contentinfo">
        <div class="site-info">
            <?php echo $sidebar_state; ?>
        </div><!-- .site-info -->
    </footer><!-- #colophon -->
</div><!-- #page -->

<?php wp_footer(); ?>
</body>
</html>

<?php echo $sidebar_state; ?> is wokring only in header.php . Any idea what should I change in my code?

Related posts

3 comments

  1. All I need was to use global variable before the declaration AND before echoing.

    <?php global $postidextra; $postidextra = "20"; ?>
    

    and then

    <?php global $postidextra; echo $postidextra; ?>
    

    Thanks G.M. for the idea.

  2. The reason that a declared global variable in header.php cannot be accessed in footer.php is because header.php and footer.php are template-part files that are included in a given template file via get_header() and get_footer(), respectively.

    Each of these template tags is a fancy wrapper for the PHP include() function. In PHP, global variables are not passed to included files, and thus cannot be referenced without being redeclared.

    The solution is simply to declare the global variable in footer.php before referencing it.

Comments are closed.