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.
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?
All I need was to use global variable before the declaration AND before echoing.
and then
Thanks G.M. for the idea.
the codex states that you can only use
get_the_id()
in the LoopThe reason that a declared global variable in
header.php
cannot be accessed infooter.php
is becauseheader.php
andfooter.php
are template-part files that are included in a given template file viaget_header()
andget_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.