admin管理员组

文章数量:1332377

I have a loop and in that loop I use a get_template_part to call the HTMl for the post to display. I also have a variable (number) to which +1 is added every time the loop runs. In this way I can track which post is displayed (for a specific layout).

            <?php $loop_post_count++ ?>

            <!-- HTML code for loop -->
            <?php get_template_part ( 'loop') ?>

This all works fine, but now I want to have an if-condition in the loop.php file which depends on the value of $loop_post_count. To be more precise, it should determine if it is the first post in the query.

I also tried using the current_post value of the query:

if ($wp_query->current_post==0) : ?> 
    <               p>FIRST POST</p>
                        <?php endif;

But that didn't work. It always outputs -1. Replacing $wp_query with $blog_posts (my variable containing the posts) outputs the same.

How do I pass a changing variable to the get_template_part or how do I check if it's the first time get_template_part is called?

Many thanks in advance!

I have a loop and in that loop I use a get_template_part to call the HTMl for the post to display. I also have a variable (number) to which +1 is added every time the loop runs. In this way I can track which post is displayed (for a specific layout).

            <?php $loop_post_count++ ?>

            <!-- HTML code for loop -->
            <?php get_template_part ( 'loop') ?>

This all works fine, but now I want to have an if-condition in the loop.php file which depends on the value of $loop_post_count. To be more precise, it should determine if it is the first post in the query.

I also tried using the current_post value of the query:

if ($wp_query->current_post==0) : ?> 
    <               p>FIRST POST</p>
                        <?php endif;

But that didn't work. It always outputs -1. Replacing $wp_query with $blog_posts (my variable containing the posts) outputs the same.

How do I pass a changing variable to the get_template_part or how do I check if it's the first time get_template_part is called?

Many thanks in advance!

Share Improve this question asked Jun 30, 2020 at 16:09 ralphjsmitralphjsmit 4026 silver badges23 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

I found an easy solution. Replacing

<?php get_template_part ( 'loop') ?>

with

<?php include( locate_template( 'loop.php', false, false ) ); ?>

did the trick. I could just use the variable as I usually would. Code and answer from mekshq.

本文标签: phpHow to pass a variable to gettemplatepart that39s updated every time the template part is called