148 posts
  • Has been part of the Envato Community for over 2 years
  • Located in Czech Republic
Itachicz says

Hi everyone,

I have this piece of chode

<?php
if ( has_post_format( 'quote' )) { ?>

    <?php get_template_part('includes/post-formats/quote-format.php'); ?>

<?php
} else if (has_post_format('gallery')) { ?>

    <?php get_template_part('includes/post-formats/gallery', 'format'); ?>

<?php
} else if (has_post_format('video')) {
   // stuff to display the link format post here
} else { ?>

    <?php get_template_part('includes/post-formats/clasic', 'format'); ?>

<?php } ?>

and in each particular template part I’m using $item_width variable. Does anyone know how to pass this variable through these functions?

Thank you very much for all advices and suggestions :)

1484 posts
  • Has referred 1+ members
  • Has sold $10,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Made it to the Authors' Hall of Fame
+3 more
OriginalEXE says

There is no way, either have your variables globally accessible, or use this instead:

include( locate_template( 'template-part.php' ) );
148 posts
  • Has been part of the Envato Community for over 2 years
  • Located in Czech Republic
Itachicz says

There is no way, either have your variables globally accessible, or use this instead:
include( locate_template( 'template-part.php' ) );

Thank you very much for your reply :)

1180 posts
  • Has been part of the Envato Community for over 4 years
  • Has sold $40,000+ on Envato Market
  • Has been a beta tester for an Envato feature
  • Has collected 50+ items on Envato Market
+5 more
Smartik says

I’ve been searching for a solution to send variable in “get_template_part” function and always without luck. I personally don’t like to use global variables because I know, this is just a bad practice. A few months ago I’ve been able to design a solution that pass Theme Check and has support for child themes. I think is a good idea to share with TF authors.
Here it is: https://github.com/Smartik89/SMK-Theme-View/blob/master/functions.php

Use it like this:
smk_get_template_part('filename.php', array(
   'variable_1' => 'Content',
   'other_variable' => 'Other content'
));
And access the variables in filename.php like this(note the $this-> prefix):
echo $this->variable_1; // Output `Content`
echo $this->other_variable; // Output `Other content`

Happy coding.

1 post
  • Has been part of the Envato Community for over 4 years
  • Has collected 1+ items on Envato Market
jachu says

Smartik why dont use include( locate_template( ‘template-part.php’ ) ); ? It is simplest…

by
by
by
by
by
by