Skip to content

Instantly share code, notes, and snippets.

@jerturowetz
Created August 20, 2019 18:40
Show Gist options
  • Save jerturowetz/98a594ca2b252128a10d4dc5b652fbe2 to your computer and use it in GitHub Desktop.
Save jerturowetz/98a594ca2b252128a10d4dc5b652fbe2 to your computer and use it in GitHub Desktop.
<?php
/**
* Functions to register client-side assets (scripts and stylesheets) for the
* Gutenberg block.
*
* @package unito-2019
*/
namespace Namespace\GutenbergBlockLoader;
/**
* Registers all block assets by iterating through folder names, so that they can be enqueued through Gutenberg in
* the corresponding context.
*
* @see https://wordpress.org/gutenberg/handbook/designers-developers/developers/tutorials/block-tutorial/applying-styles-with-stylesheets/
*/
function blocks_init() {
// Skip block registration if Gutenberg is not enabled/merged.
if ( ! function_exists( 'register_block_type' ) ) {
return;
}
$parent_folder = plugin_dir_path( __FILE__ );
$folders = glob( "$parent_folder*", GLOB_ONLYDIR );
foreach ( $folders as $folder_full_path ) {
$folder_name = str_replace( $parent_folder, '', $folder_full_path );
$block_name = strtolower( $folder_name );
$build_folder = '/assets/build';
wp_register_script(
"$block_name-block-editor",
get_template_directory_uri() . "$build_folder/block-$block_name-index.min.js",
[ 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' ],
filemtime( "$folder_full_path/index.js" ),
false
);
wp_register_style(
"$block_name-block-editor",
get_template_directory_uri() . "$build_folder/block-$block_name-editor-style.min.css",
[],
filemtime( "$folder_full_path/editor-style.scss" )
);
$style_css = 'style.css';
wp_register_style(
"$block_name-block",
get_template_directory_uri() . "$build_folder/block-$block_name-style.min.css",
[],
filemtime( "$folder_full_path/style.scss" )
);
register_block_type(
"unito/$block_name",
[
'editor_script' => "$block_name-block-editor",
'editor_style' => "$block_name-block-editor",
'style' => "$block_name-block",
]
);
}
}
add_action( 'init', __NAMESPACE__ . '\\blocks_init' );
/**
* Load blocks helpers
*/
function load_block_helpers() {
$file_list = recursive_file_search( plugin_dir_path( __FILE__ ), '/^.*.php$/' );
foreach ( $file_list as $file ) {
include_once $file;
}
}
add_action( 'after_setup_theme', __NAMESPACE__ . '\\load_block_helpers', 0 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment