WP SITES

3082 Coded Tutorials & 283 Plugins

Testing Dynamic Block Attribute Rendering

This PHP code enables you to test the values for your attribute key output on the frontend for debugging and development.

Add this in block.php or your main block plugins .php file :

function render_block_attribute_color($attributes) {

    $star_color = isset($attributes['starColor']) ? esc_attr($attributes['starColor']) : '#ffcc00';

    return '<p ' . get_block_wrapper_attributes(['style' => 'color: ' . $star_color . ';']) . '>
        <strong>Color:</strong> ' . $star_color . '
        <span style="color: ' . $star_color . ';">★★★★★</span></p>';
}

register_block_type('my-plugin/my-custom-block-type', [
    'render_callback' => 'render_block_attribute_color',
]);

Add the following PHP code to your render.php file, in your scr folder NOT build folder.

<p <?php echo get_block_wrapper_attributes(); ?>>
<?php echo render_block_attribute_color($attributes); ?>
</p>

Swap Outs

  • Make sure you swap out the $attribute keys in the above code to match your own.
  • Make sure you swap out the value for the render_callback function with your own
  • Mare sure you swap out the 2 register_block_type parameters to match your own namespace blockname.

You may also need CSS like this in your src folders style.scss file :

.star-rating {
    color: var(--star-color);
}

Now you can dynamically test your block editor attribute settings output on the frontend. The code uses the saved value from the block editor on the frontend.

I’m using this to add a custom color setting to the block settings for the Product Category Star Rating Plugin which you can see in the above image ( right sidebar ) for styling the stars using Gutenberg.

Leave a Reply

New Plugins