Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example plugin file for enqueueing Gutenberg block JS and CSS
<?php
/**
* Enqueue block editor JavaScript and CSS
*/
function jsforwpblocks_editor_scripts() {
// Make paths variables so we don't write em twice ;)
$blockPath = '/assets/js/blocks.js';
$editorStylePath = '/assets/css/blocks.editor.css';
// Enqueue the bundled block JS file
wp_enqueue_script(
'jsforwp-blocks-js',
plugins_url( $blockPath, __FILE__ ),
[ 'wp-blocks', 'wp-element', 'wp-components', 'wp-i18n' ],
filemtime( plugin_dir_path( __FILE__ ) . $blockPath )
);
// Enqueue optional editor only styles
wp_enqueue_style(
'jsforwp-blocks-editor-css',
plugins_url($editorStylePath, __FILE__),
[ 'wp-blocks', 'wp-element', 'wp-components', 'wp-i18n' ],
filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath )
);
}
// Hook scripts function into block editor hook
add_action( 'enqueue_block_editor_assets', 'jsforwpblocks_editor_scripts' );
/**
* Enqueue block editor JavaScript and CSS
*/
function jsforwpblocks_scripts() {
// Make paths variables so we don't write em twice ;)
$sharedBlockPath = '/assets/js/blocks.shared.js';
$stylePath = '/assets/css/blocks.style.css';
$frontendStylePath = '/assets/css/blocks.frontend.css';
// Enqueue frontend and editor JS
wp_enqueue_script(
'jsforwp-blocks-frontend-js',
plugins_url( $sharedBlockPath, __FILE__ ),
[ 'wp-blocks', 'wp-element', 'wp-components', 'wp-i18n' ],
filemtime( plugin_dir_path( __FILE__ ) . $sharedBlockPath )
);
// Enqueue frontend and editor block styles
wp_enqueue_style(
'jsforwp-blocks-css',
plugins_url($stylePath, __FILE__),
[ 'wp-blocks', 'wp-element', 'wp-components', 'wp-i18n' ],
filemtime( plugin_dir_path( __FILE__ ) . $stylePath )
);
// Enqueue frontend only CSS
if( !is_admin() ) {
wp_enqueue_style(
'jsforwp-blocks-frontend-css',
plugins_url($frontendStylePath, __FILE__),
[ 'wp-blocks', 'wp-element', 'wp-components', 'wp-i18n' ],
filemtime( plugin_dir_path( __FILE__ ) . $frontendStylePath )
);
}
}
// Hook scripts function into block editor hook
add_action( 'enqueue_block_assets', 'jsforwpblocks_scripts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment