Skip to content

Instantly share code, notes, and snippets.

@pbearne
Last active March 15, 2024 11:42
Show Gist options
  • Save pbearne/2009f8cf8fc5416dd6f2bd4d821a94f6 to your computer and use it in GitHub Desktop.
Save pbearne/2009f8cf8fc5416dd6f2bd4d821a94f6 to your computer and use it in GitHub Desktop.
code to force server-side Gutenberg block to reload on a change to a Tax
/**
* BLOCK: serverside block that changes on page tax
*
* Registering a basic block with Gutenberg.
* Simple block, renders and saves the same content without any interactivity.
*/
// Import CSS.
import './editor.scss';
import './style.scss';
const {__} = wp.i18n; // Import __() from wp.i18n
const {registerBlockType} = wp.blocks; // Import registerBlockType() from wp.blocks
const {ServerSideRender, Spinner, SelectControl} = wp.components;
const {withSelect} = wp.data;
/**
* Register: aa Gutenberg Block.
*
* Registers a new block provided a unique name and an object defining its
* behavior. Once registered, the block is made editor as an option to any
* editor interface where blocks are implemented.
*
* @link https://wordpress.org/gutenberg/handbook/block-api/
* @param {string} name Block name.
* @param {Object} settings Block settings.
* @return {?WPBlock} The block, if it has been successfully
* registered; otherwise `undefined`.
*/
registerBlockType('example/block-server-side', {
// Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
title: __('serverside block that changes on page tax'), // Block title.
icon: 'admin-site-alt', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
category: 'common', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
keywords: [
__('serverside'),
__('dynamic'),
],
/**
* The edit function describes the structure of your block in the context of the editor.
* This represents what the editor will render when the block is used.
*
* The "edit" property must be a valid function.
*
* @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
*
* @param {Object} props Props.
* @returns {Mixed} JSX Component.
*/
edit: withSelect( select => {
return {
// this the magic this code listens to tax in cause a custom tax called resorts the deafult is 'tags'
tax: wp.data.select( 'core/editor' ).getEditedPostAttribute( 'resorts' )
};
} ) ( (props) => {
const {
className, tax
} = props;
// if we have no tax set for the page then just show a messege to save a call to server side
if ( 0 === tax.length ) {
return <p>{ __( 'Select the resort in the sidebar, 'mvc' ) }</p>;
}
// the server side block with the tax object getting passed
return (
<div className={className}>
<ServerSideRender block="mvc/block-mvc-landing-pages-title"
attributes={ { tax: tax } }
/>
</div>
);
}),
/**
* The save function defines the way in which the different attributes should be combined
* into the final markup, which is then serialized by Gutenberg into post_content.
*
* The "save" property must be specified and must be a valid function.
*
* @link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
*
* @param {Object} props Props.
* @returns {Mixed} JSX Frontend HTML.
*/
save: (props) => {
return null;
},
});
<?php
namespace example;
class Render {
public function __construct() {
add_action( 'plugins_loaded', [ $this, 'register_dynamic_block' ] );
}
/**
* Register the dynamic block.
*
* @return void
* @since 2.1.0
*
*/
public function register_dynamic_block() {
// Only load if Gutenberg is available.
if ( ! function_exists( 'register_block_type' ) ) {
return;
}
// Hook server side rendering into render callback
register_block_type( 'mvc/block-mvc-landing-pages-title',
[
// add the tax to the allowed attributes in this case we got an array
'attributes' => [
'tax' => [
'type' => 'array',
],
],
'render_callback' => [ $this, 'render_dynamic_block' ],
]
);
}
/**
* Server rendering for mvc/block-mvc-landing-pages-title
*/
public function render_dynamic_block( $att ) {
// defaults return values
$resort_name = 'No resort set';
$location_name = 'No location set';
// did we get a tax passed to us if lets use it
if ( isset( $att['tax'] ) ) {
// the object we get from editor is/maybe an array you have to check it out to workout what to extract
$terms[] = get_term_by( 'term_id', $att['tax'][0], 'resorts' );
} else {
// if not then lets terms for the page and render that
$terms = get_the_terms( get_the_ID(), 'resorts' );
}
If ( false !== $terms ) {
// get the term meta and set the loaction
$tax_meta = get_term_meta( $terms[0]->term_id );
if ( ! empty( $tax_meta ) && isset( $tax_meta['location'] ) ) {
$location_name = $tax_meta['location'][0];
}
// set the resort name
$resort_name = $terms[0]->name;
}
return sprintf( '<div class="resort-title"><h1>%s</h1><h2>%s</h2></div>',
esc_html( $resort_name ),
esc_html( $location_name )
);
}
}
@pbearne
Copy link
Author

pbearne commented Jan 14, 2020

the working code after the help I got in this ticket
WordPress/gutenberg#19486

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment