Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

Adding Post ID as Data Attribute to Dynamic Image in Content-Loop Element

  • Hi Guys
    I am working on a project where I need to add the post ID as a data attribute to dynamic images within a content-loop element. Specifically, the targeted element is a dynamic image with a dynamic link to its post, and it is contained within a block that has the classname .query-loop-icon.

    Here is an example of the HTML structure we are working with:

    <div class="gb-container">
        <figure class="gb-block-image">
            <a href="">
                <img data-post-id="1234" src="" class="query-loop-icon" alt="">

    I have implemented a custom render_block filter in WordPress to achieve this, but I would like to know if GenerateBlocks already provides a built-in filter or hook that can add the post ID to the image dynamically without custom coding.

    Here is the custom filter I am currently using:

    add_filter('render_block', function($block_content, $block) {
        if (!is_admin() && isset($block['attrs']['className']) && strpos($block['attrs']['className'], 'query-loop-icon') !== false) {
            if (get_post_type() === 'icon') {
                $post_id = get_the_ID();
                $block_content = preg_replace('/<img\s/', '<img data-post-id="' . $post_id . '" ', $block_content);
        return $block_content;
    }, 10, 2);

    This filter works well, but I’m interested in knowing if there is a more streamlined or officially supported way to achieve this within the GenerateBlocks framework.

    Any guidance or suggestions you can provide would be greatly appreciated.

    Thank you for your assistance!
    best, Sam

  • Hi Sam,

    Your method is what I would do, there isn’t an option to achieve this without coding, unfortunately.

  • got it, thanks Ying.

  • No Problem 🙂

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