Attributes in a Dynamic Custom Block

[ad_1]

How do you access $attributes from a dynamic custom block PHP file?

Accessing attributes in a static custom block via JS is really simple. However I’m unable to access attributes in a dynamic custom block via PHP.

I’m using the @wordpress/create-block (@wordpress/scripts v25.1.0) to get started with dynamic blocks:

npx @wordpress/create-block --variant dynamic todo-list

In this latest version, you are provided with a render.php file. Not sure how you are meant to return the attributes within this file. Can’t find any docs on this:

<?php

global $block;

$attributes = $block['attrs'];
// $attributes = $block->get_attributes();

print_r($attributes);

?>
<div <?php echo get_block_wrapper_attributes(); ?>>
	<?php esc_html_e('My Dynamic Block – hello from a dynamic block!', 'my-dynamic-block'); ?>
</div>

Failing that, I’ve gone back into the main php where the block is registered and have tried hooking into the render_callback since this should be able to return the attributes , content and block:

function register_dynamic_block()
{
    register_block_type(
        __DIR__ . '/build',
        array('render_callback' => 'my_callback')
    );
}
add_action('init', 'register_dynamic_block');

function my_callback($attributes, $content, $block)
{
    print_r($attributes); 
   // Can't even access attributes in here! :S
}

But this also just prints an empty array Array()

Anyone have any ideas as to how you are meant to retrieve attributes from the render.php file?

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer