What is best way passing variables to theme templates and using them different places like widgets?

I have a template file at /parts/template.php
which contains a post listing code like,

echo get_the_title(); //same lines with my_render_function

and i am using it at archive.php with this lines.

while ( have_posts() ) : the_post();
  get_template_part('template');
endwhile;

But now i wrote a widget and a shortcode.
My widget and shortcode using a function called shared_listing()

function shared_listing(){
  $posts=get_posts();
  my_render_function($posts);
}

function my_render_function($posts){
  foreach($posts as $post) {
    echo get_the_title($post->ID); //same lines with template.php except $post->ID
  }
}

so, i found a solution. i removed template.php and changed archive.php to this.

if ( have_posts() ) : 
  my_render_function($posts);
endif;

Now, my archive.php, my widget and my shortcode uses the same template with my_render_function(). And i created a file called my_render_function.php and after adding the function lines i copied it into parts folder.

And i didnt use this lines at widget and shortcode and changed template to render function because i need pass $posts and some other variables too. Because of design $post_count is one of them. And without using a loop at the point where frontend codes in, it doesnt makes any sense. and i need to make it right. Not with hacks for sure.

setup_postdata( $post );
get_template_part('template');

So now my question;

in the begining i was using get_the_title(); at template.php and get_the_title($post->ID); at widget and shortcode loop.
but now im using get_the_title($post->ID) at all of them.

1- is that makes my system more slower?

There is an object cache mechanism in wp, so it shouldnt affect, i believe.

in the beginning i was using get_template_part() at archive.php with have_posts() and foreach render function at shortcode and widget.
now im using include() (only once at function.php) and foreach render function at all of them.

2- is it the best way to make it right? or are there any other logical and high performance solution to do this?

sorry for my poor english and thank you for reading.

1 Answer
1

1 If you look at the source code of get_the_title you will see that there is no difference between the two ways of writing the same thing, because if you call it without a parameter it is supposed to be the current ID.

2 There is no substantial difference between the two loops you use. All go through the same amount of items and do the same thing with it. Theoretically putting everything in archive.php would be a bit faster, because you skip the function call to get_template_part().

In short: when it comes to performance the two options are hardly any different.

Leave a Comment