-
Notifications
You must be signed in to change notification settings - Fork 0
/
extending-gutenberg.php
60 lines (48 loc) · 1.68 KB
/
extending-gutenberg.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
/*
Plugin Name: Extending Gutenberg
Description: A sample plugin on how to extend existing Gutenberg blocks
Theme URI: https://marcuskober.de
Author: Marcus Kober
Author URI: https://marcuskober.de
Version: 1.0.0
Text Domain: extending-gutenberg
*/
declare(strict_types=1);
if (! defined('ABSPATH')) {
exit;
}
define('EXTGUT_DIR', plugin_dir_path(__FILE__));
define('EXTGUT_URL', plugin_dir_url(__FILE__));
add_action('enqueue_block_editor_assets', function() {
$config = require_once EXTGUT_DIR . '/build/index.asset.php';
wp_enqueue_script(
'extending-gutenberg-script',
EXTGUT_URL . '/build/index.js',
$config['dependencies'],
$config['version']
);
});
add_filter('render_block', function(string $blockContent, array $block): string {
if ($block['blockName'] !== 'core/paragraph' || ! isset($block['attrs']['extendedSettings'])) {
return $blockContent;
}
// Check if block has id
$blockHasId = preg_match('/id="([^"]+)"/', $blockContent, $matches);
if ($blockHasId) {
$id = $matches[1];
}
else {
// Create new block id
$id ='extgut-' . uniqid();
$blockContent = preg_replace('#^<([^>]+)>#m', '<$1 id="' . $id . '">', $blockContent);
}
// Create css
$style = sprintf(
'<style>#%s{column-count:%s; column-gap:%s;}</style>',
$id,
isset($block['attrs']['extendedSettings']['columnCount']) ? $block['attrs']['extendedSettings']['columnCount'] : 1,
isset($block['attrs']['extendedSettings']['columnGap']) ? $block['attrs']['extendedSettings']['columnGap'] : '20px'
);
return $style.$blockContent;
}, 10, 2 );