Share value between core and different pages

[ad_1]

I start every post of my blog with an include file. So when the user lists “all posts” on one page, this header will show up many times. In order to avoid this I set up a global variable ( $GLOBALS[‘my_array’][‘1’], initiated on “parse_query” hook) that keeps track of how many posts have been listed, so that the header is only displayed for the first post listed on every page.

I need to access the value in each individual post being listed.

Now I try to upgrade to PHP8 and this kind of global is deprecated. Which would be the easiest way to keep track of how many posts have been listed on a page containing “all posts”.

I believe this is the loop I wish to count and access the value in all individual posts:

if ( have_posts() ) {

    while ( have_posts() ) {
        the_post();

        get_template_part( 'template-parts/content', get_post_type() );
    }
}

(singular.php from twentytwenty theme)

How can I set a counter for this loop and pass the value into the individual posts. (And zero the counter for every time this page loads.)

(I have started experimenting with static variables, but I am not through with it yet.)

Thank you

  • This topic was modified 21 hours, 33 minutes ago by sweden1.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer