Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

WordPress – Access php variables from another file within an html file

I have a page with several tabs and to keep things organized I have one file for the overall page template and one for each tab that will be opened. When pressing the tabs I hide/unhide (with the class hidden which sets display: none) sections which is originally placed like this in my page_template.php file:

<div id="content-wrapper">
    <section id="page_tab_1">
        <?php get_template_part( 'page/page_tab_1' ); ?>
    </section>
    <section id="page_tab_2" class="hidden">
        <?php get_template_part( 'page/page_tab_2' ); ?>
    </section>
</div>

Now I want to use a variable in both page_template.php and page_tab_1.php. When placing $my_variable = 'Test'; at the top of the page_template.php I can of course use it below with e.g. <?php echo $my_variable; ?>, but when I try to echo it in page_tab_1.php it doesn’t work.

I solved it by adding functions at the top of page_template.php like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function get_my_variable(){return 'Test';}

Then I can use the following code in both files:

$my_variable = get_my_variable();

The reason I don’t want to put $my_variable = 'Test'; in both files is because some of the real variables take some calculations and I don’t want to duplicate too much code.

Question

I thought I could just declare the variables at the top of page_template.php since the other code is pasted below that, but I guess that is not how get_template_part works. So is there a more elegant/smart way to declare variables in page_template.php which can then be used by all page_tab_x.php files?

>Solution :

get_template_part let you pass additional arguments to the template through the third parameter $args.

@see https://developer.wordpress.org/reference/functions/get_template_part/

get_template_part(
    'template-part',
    'name',
    array(
        'key1'  => $myValue1,
        'key2'  => 'myValue2',
    )
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading