[Resolved] Getting current post in a hook inside Query Loop in GenerateBlocks

Home Forums Support [Resolved] Getting current post in a hook inside Query Loop in GenerateBlocks

Home Forums Support Getting current post in a hook inside Query Loop in GenerateBlocks

Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #2332848
    Zarar

    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.

    #2333010
    David
    Staff
    Customer Support

    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.

    #2333205
    Zarar

    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!

    #2333287
    David
    Staff
    Customer Support

    Glad to be of help 🙂

    #2333348
    Zarar

    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.

    #2333412
    Fernando
    Customer Support

    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.

    #2339233
    Zarar

    Thank you. This works!

    #2339984
    Fernando
    Customer Support

    You’re welcome Zarar!

Viewing 8 posts - 1 through 8 (of 8 total)
  • You must be logged in to reply to this topic.