148 posts
  • Czech Republic
  • Has been a member for 2-3 years
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 :)

1465 posts
  • Has been a member for 2-3 years
  • Exclusive Author
  • Sold between 10 000 and 50 000 dollars
  • Bought between 10 and 49 items
  • Referred between 1 and 9 users
  • Croatia
OriginalEXE says

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

include( locate_template( 'template-part.php' ) );
148 posts
  • Czech Republic
  • Has been a member for 2-3 years
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 :)

1067 posts
  • Forum Superstar
  • Most Wanted Bounty Winner
  • Envato Studio (Microlancer) Beta Tester
  • Author had a Free File of the Month
  • Bought between 50 and 99 items
  • Referred between 50 and 99 users
  • Europe
  • Has been a member for 3-4 years
  • Exclusive Author
+1 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.

by
by
by
by
by
by