Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

How to use get_theme_mod in gutenberg editor wordpress?

Writer Matthew Harrington

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>;
}

1 Answer

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:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.