Add product attribute to Woocommerce’s blocks in Gutenberg
It seems that WordPress has some good guides for adding custom attributes to their blocks.
This and this for example.
In their case, in one of the guides, they add the radio button, if you for example want to ‘hide this block on mobile’. And then a CSS-class will be added to the block when it is created. A bit long code, but it can be done.
But how to do it for the Woocommerce Block plugin?
I want to be able to show a product attribute in the newest products block for each product. Only if it exists.
I can’t seem to find any documentation from Woocommerce for doing this. You already have the ability to show/hide name, review, add-to-cart button in the backend, when you choose the block, but how to extend this functionality?
What the guides have shown
You add a filter to add a new functionality to a Gutenberg Block:
addFilter(
'blocks.registerBlockType',
'editorskit/custom-attributes',
addAttributes
);
What will this look like, if it was Woocommerce?
And the addAttribute function look like this:
function addAttributes( settings ) {
//check if object exists for old Gutenberg version compatibility
if( typeof settings.attributes !== 'undefined' ){
settings.attributes = Object.assign( settings.attributes, {
visibleOnMobile:{
type: 'boolean',
default: true,
}
});
}
return settings;
}
Can i call a product attribute from this code? Or how should i do it?
Does the global $product
work?
So i could do this with size, for example:
global $product;
$size = array_shift( wc_get_product_terms( $product->id, 'size', array( 'fields' => 'names' ) ) );
Leave an answer