Site logo

Archived topic

Print the index of the query loop as an attribute or class of an element

3 replies · Started by Zarar on September 10, 2022

Viewing posts 1–4 of 4

I have a Query Loop which prints 8 headlines, and I want to configure Google Analytics so that I know which of the 8 headlines was clicked. The first, second etc...

My approach here was to figure out a way to print 0....7 as part of a class or attribute of an element, but I don't seem to have access to this information. Something like

<a class=“item0” href="...">Headline 0</a>
<a class=“item1” href="...">Headline 1</a>

Is this possible? Thank you.

So I tried the following to print the index of the current post as part of the CSS class names, but $wp_query->current_post returns 0 every time. This is probably because generatepress or generateblocks isn't use the main query but creating a custom one. Any idea on how to get that the current query?

add_filter( 'render_block', function( $block_content, $block ){
    global $wp_query;
    $className = 'rr-analytics-home-primary-article';
    if ( ! empty( $block['attrs']['className'] ) && $className === $block['attrs']['className']  ) {
        return str_replace($className, $className . " " . $wp_query->current_post , $block_content);
    }
	return $block_content;
}, 10, 2);

I ended up not needing this as I added a custom CSS class outside the Query Loop at the Grid level and then used the following CSS selectors in Google Analytics/Tag Manager to detect which image was clicked:

.primary-articles-container .gb-query-loop-item:nth-of-type(2) figure a

I see. Glad you found a solution Zarar!

This archived topic is closed to new replies.