Skip to content

Instantly share code, notes, and snippets.

@zgordon
Last active September 27, 2022 09:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save zgordon/561a82424e677a3b466d63fb588dddeb to your computer and use it in GitHub Desktop.
Save zgordon/561a82424e677a3b466d63fb588dddeb to your computer and use it in GitHub Desktop.
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