How to declare a variable in a loop and make it available in the template file

I was faced with a minor issue but can't solve it myself. I need to add the value on the variable after all loop iterations. And nothing problem, but I need to use this variable in the other file. for example:

while( have_posts() ) {
        the_post();
        $x = '';
        $x++;
        get_template_part( 'content', 'right' );
    }

Now I need to get the $x value with iteration in content-right.php I try to declare a variable into this file but in this case no iteration. Is there any way to solve this?

Topic get-template-part loop Wordpress

Category Web


You are re-initializing your $x variable on every iteration of the loop. Maybe you want to move its initialization outside the loop? To get $x variable value in the content-right.php file you can declare it as global:

global $x;
$x = 0;
while( have_posts() ) {
    the_post();
    $x++;
    get_template_part( 'content', 'right' );
}

Then you can use it in the content-right.php file:

global $x;
# ... here you can use $x variable value

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.