Created
February 11, 2023 19:18
-
-
Save thesandybridge/4c97190a7a7cd62c9912a9bdbd99fb50 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @package GrafikBasePlugin | |
*/ | |
namespace Lib\Services\Components; | |
use Lib\Services\ServicesBase; | |
use Lib\Services\Service; | |
/** | |
* Register functionality for Grafik Blocks. | |
* @package Lib\Services\Components | |
*/ | |
class Blocks extends ServicesBase implements Service { | |
public function register() { | |
add_action( 'init', [$this, 'init_blocks'] ); | |
add_action( 'enqueue_block_assets', [$this, 'enqueue_assets'] ); | |
add_filter( 'block_categories_all', [$this, 'create_block_categories'] ); | |
} | |
function return_blocks_data() { | |
return json_decode( | |
file_get_contents(GRAFIK_WP_PLUGIN_PATH . 'grafik-blocks.json'), | |
true | |
); | |
} | |
public function init_blocks() { | |
// Require the render callbacks for each dynamic block. | |
require_once GRAFIK_WP_PLUGIN_PATH . 'app/render_callbacks/render_callbacks.php'; | |
$path_to_blocks = GRAFIK_WP_PLUGIN_PATH . 'app/blocks'; | |
$blocks = $this->return_blocks_data(); | |
// Loop through the decoded blocks and register them according to the block type | |
foreach ( $blocks ?? [] as $key => $val ) { | |
switch ($key) { | |
case 'static': | |
foreach ( $val ?? [] as $block ) { | |
register_block_type( | |
"{$path_to_blocks}/{$key}/{$block}" | |
); | |
} | |
break; | |
case 'dynamic': | |
foreach ( $val ?? [] as $block => $render_callback ) { | |
register_block_type( | |
"{$path_to_blocks}/{$key}/{$block}", | |
array( | |
'render_callback' => $render_callback, | |
) | |
); | |
} | |
break; | |
} | |
} | |
} | |
public function enqueue_assets() { | |
$blocks = $this->return_blocks_data(); | |
foreach ( $blocks['dynamic'] ?? [] as $key => $val ) { | |
$path = GRAFIK_WP_PLUGIN_PATH . "build/blocks/{$key}/front-end.js"; | |
if ( !file_exists( $path ) ) return; | |
$label = "{$key}_front_end_script"; | |
wp_register_script( | |
$label, | |
GRAFIK_WP_PLUGIN_PATH . "build/blocks/{$key}/front-end.js", | |
[], | |
filemtime($path), | |
); | |
if ( has_block( "grafik-blocks/{$key}" ) ) { | |
wp_enqueue_script( $label ); | |
} | |
} | |
} | |
/** | |
* Register the category for the Blocks | |
*/ | |
public function create_block_categories( $categories ) { | |
return array_merge( | |
[ | |
[ | |
'slug' => 'grafik-blocks', | |
'title' => __( 'Grafik Blocks', 'grafik-blocks' ), | |
], | |
], | |
$categories, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment