admin管理员组

文章数量:1277901

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?

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?

Share Improve this question asked Sep 24, 2021 at 18:18 Victor SokoliukVictor Sokoliuk 1397 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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

本文标签: How to declare a variable in a loop and make it available in the template file