Site logo

Archived topic

Getting current post in a hook inside Query Loop in GenerateBlocks

7 replies · Started by Zarar on September 4, 2022

Viewing posts 1–8 of 8

I have a custom hook which is nested inside a Query Loop and would like to have access to the current post information. Basically:

    add_shortcode( 'comment-link', function() {
        ob_start();
	    echo "..."; // how do I print current post's permalink here?
        return ob_get_clean();
    } );

Thank you for reading.

Hi there,

dynamic shortcodes won't work inside the Query Loop, the same goes for the core query loop block, theres some limitations within Gutenberg.

Instead of using a shortcode you can use the render_block filter hook to replace the blocks content.
Here an example:

add_filter( 'render_block', function( $block_content, $block ) {

    if ( ! empty( $block['attrs']['className'] ) && 'your-class' === $block['attrs']['className']  ) {
		
        $block_content = 'return your content here';

    }

    return $block_content;

}, 10, 2 );

So you can add a block eg. a Headline Block, give it a CSS class in the advanced tab.
In the code above swap your-class for that class name.

And that method will pass the current post ID.

That's a great workaround. I did end up solving this by making the Container block dynamic but this is a great tip to keep in mind for next time. Thank you!

Glad to be of help :)

Actually David, when you say "And that method will pass the current post ID", which variable will it be stored in? The $block variable doesn't appear to have it.

Hi Zarar,

It won't be there. It just means that if you use get_the_ID() for instance, that should work.

So, you'll need to add a variable to store the current post ID.

Thank you. This works!

You're welcome Zarar!

This archived topic is closed to new replies.