In my old WordPress themes (before Gutenberg) I used get_theme_mod
to get custom values for certain things in the theme.
get_theme_mod( 'news_custom_headline' );
Now I would like to use the gutenberg editor, however still want to access data from the customizer. How can I do something like this:
save({ attributes }) {
return <p>Value from backend: get_theme_mod( 'news_custom_headline' ) </p>;
}
You don't do that like this. I got it working with a server side rendered block:
In my index.js
:
registerBlockType('test/custom-php-render-block', {
title: "Custom Block Server Side Rendering",
category: 'widgets',
edit: () => { return <p>This is just a placeholder!</p>},
save: () => { return null }
});
In functions.php
:
function register_my_custom_block() {
wp_register_script( 'custom-block-php-script', get_template_directory_uri() . '/build/index.js', array('wp-blocks', 'wp-editor'));
wp_enqueue_script('custom-block-php-script');
register_block_type('test/custom-php-render-block', [
'editor_script' => 'custom-block-php-script',
'render_callback' => 'custom_block_php-render'
]);
}
add_action( 'init', 'register_my_custom_block');
function custom_block_php-render($attr, $content) {
return '<p>From customizer: ' . get_theme_mod('your-setting') . '</p>';
}
You can read more about this here: https://awhitepixel.com/blog/wordpress-gutenberg-create-custom-block-part-9-dynamic-blocks-php-render/