websevendev / attributes-for-blocks

WordPress plugin that allows to add custom HTML attributes to Gutenberg blocks.
https://wordpress.org/plugins/attributes-for-blocks/
GNU General Public License v2.0
24 stars 6 forks source link

dynamic value in the attributes #6

Open xu4wang opened 1 week ago

xu4wang commented 1 week ago

Is it possible to assign dynamic values to an attribute? for example

x-data = { href: '{{post_permalink}}' }

I am trying to use it inside a loop.

websevendev commented 1 week ago

Doesn't look like it, there is no filter in place. I suppose there could be one here:

https://github.com/websevendev/attributes-for-blocks/blob/42e73d1c31ba6ab98b223f624b901ad9d1026918/attributes-for-blocks.php#L163

So replace it with:

    return apply_filters('afb_get_attributes', $attributes, $args, $tags);

(I'll include it in the next release so it won't disappear with a plugin update) and then you can use something like:

add_filter('afb_get_attributes', function($attributes) {
    foreach($attributes as $key => $value) {
        $attributes[$key] = str_replace('{{my_dynamic_permalink}}', esc_js(get_the_permalink()), $value);
    }
    return $attributes;
});

Alternatively you could locate the dynamic value with AlpineJS on the page, if it's available:

<!-- wp:query -->
    <div class="wp-block-query">
    <!-- wp:post-template -->
        <!-- wp:post-title {"isLink":true,"attributesForBlocks":{"x-cloak":""}} /-->
        <!-- wp:post-date {"attributesForBlocks":{"x-data":"{href: $el.previousElementSibling.querySelector('a').getAttribute('href')}","x-text":"href"}} /-->
    <!-- /wp:post-template -->
    </div>
<!-- /wp:query -->