PluginProbe
Blockenberg — 600+ Advanced Gutenberg Blocks & AI Agent for WordPress Block Editor / 2.0.13
Blockenberg — 600+ Advanced Gutenberg Blocks & AI Agent for WordPress Block Editor v2.0.13
2.0.13 2.0.12 2.0.11 2.0.10 2.0.9 trunk 2.0.2 2.0.3 2.0.4 2.0.5 2.0.6 2.0.7 2.0.8
blockenberg / blockenberg.php

blockenberg.php in Blockenberg — 600+ Advanced Gutenberg Blocks & AI Agent for WordPress Block Editor 2.0.13, at blockenberg.php

1,295 lines 55.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Plugin Name: Blockenberg — 600+ Advanced Gutenberg Blocks & AI Agent for WordPress Block Editor
4 * Description: Advanced Gutenberg Blocks and an AI Agent for the WordPress Block Editor
5 * Version: 2.0.13
6 * Author: Blockenberg
7 * Text Domain: blockenberg
8 * Domain Path: /languages
9 * License: GPLv2 or later
10 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
11 */
12
13 defined( 'ABSPATH' ) || exit;
14
15 /**
16 * Ensure enough PHP memory to register 600+ blocks with layout attributes.
17 * The register_block_type_args filter adds ~400 extra attributes per block,
18 * which requires significantly more memory than the WordPress default 128M.
19 */
20 @ini_set( 'memory_limit', '512M' );
21
22 /**
23 * Google Fonts list for the Typography Control.
24 */
25 require_once __DIR__ . '/assets/php/google-fonts.php';
26
27 /**
28 * User Field block — dynamic PHP render for logged-in profile values.
29 */
30 require_once __DIR__ . '/blocks/user-field/render.php';
31
32 /**
33 * AI Agent — OpenRouter-powered chat panel inside the block editor.
34 */
35 require_once __DIR__ . '/assets/php/ai-assistant.php';
36 require_once __DIR__ . '/assets/php/ai-external.php';
37
38 /**
39 * Admin dashboard — Block Manager (enable / disable blocks).
40 */
41 if ( is_admin() ) {
42 require_once __DIR__ . '/assets/php/admin-dashboard.php';
43 }
44
45 /**
46 * Enqueue common editor styles and scripts for all Blockenberg blocks
47 */
48 add_action( 'enqueue_block_editor_assets', function() {
49 wp_enqueue_style( 'dashicons' );
50 // Ensure Media Library modal assets are available for blocks using MediaUpload.
51 wp_enqueue_media();
52
53 // Common editor scripts (branded icons)
54 $editor_js = __DIR__ . '/assets/js/editor.js';
55 if ( file_exists( $editor_js ) ) {
56 wp_enqueue_script(
57 'bkbg-editor-common',
58 plugins_url( 'assets/js/editor.js', __FILE__ ),
59 array( 'wp-blocks', 'wp-dom-ready', 'wp-element' ),
60 filemtime( $editor_js ),
61 true
62 );
63 }
64
65 // Inspector tabs (General / Advanced) for all Blockenberg blocks
66 $inspector_tabs_js = __DIR__ . '/assets/js/inspector-tabs.js';
67 if ( file_exists( $inspector_tabs_js ) ) {
68 wp_enqueue_script(
69 'bkbg-inspector-tabs',
70 plugins_url( 'assets/js/inspector-tabs.js', __FILE__ ),
71 array( 'wp-blocks', 'wp-element', 'wp-compose', 'wp-hooks', 'wp-block-editor', 'wp-components', 'wp-i18n', 'wp-data' ),
72 filemtime( $inspector_tabs_js ),
73 true
74 );
75 }
76
77 // Typography Control — shared Elementor-like popover for all blocks
78 // Registered on init (so block scripts can safely depend on it).
79 wp_enqueue_script( 'bkbg-typography-control' );
80 });
81
82 /**
83 * Register shared editor scripts early (so other scripts can list them as deps).
84 */
85 add_action( 'init', function () {
86 $typo_js = __DIR__ . '/assets/js/typography-control.js';
87 if ( ! file_exists( $typo_js ) ) {
88 return;
89 }
90
91 wp_register_script(
92 'bkbg-typography-control',
93 plugins_url( 'assets/js/typography-control.js', __FILE__ ),
94 array( 'wp-element', 'wp-components', 'wp-i18n' ),
95 filemtime( $typo_js ),
96 true
97 );
98
99 // Pass Google Fonts list to JS as window.bkbgGoogleFonts
100 wp_localize_script(
101 'bkbg-typography-control',
102 'bkbgGoogleFonts',
103 function_exists( 'bkbg_google_fonts_list' ) ? bkbg_google_fonts_list() : array()
104 );
105
106 // Icon Picker — shared icon type selector + dashicon picker for all blocks
107 $icon_picker_js = __DIR__ . '/assets/js/icon-picker.js';
108 if ( file_exists( $icon_picker_js ) ) {
109 // Editor handle (needs WP component deps for UI)
110 wp_register_script(
111 'bkbg-icon-picker',
112 plugins_url( 'assets/js/icon-picker.js', __FILE__ ),
113 array( 'wp-element', 'wp-components', 'wp-i18n' ),
114 filemtime( $icon_picker_js ),
115 true
116 );
117 // Frontend handle (same file, no WP deps — only data + DOM builder)
118 wp_register_script(
119 'bkbg-icon-picker-frontend',
120 plugins_url( 'assets/js/icon-picker.js', __FILE__ ),
121 array(),
122 filemtime( $icon_picker_js ),
123 true
124 );
125 }
126 } );
127
128 /**
129 * Enqueue editor styles in a way compatible with the iframe-based editor canvas.
130 */
131 add_action( 'enqueue_block_assets', function () {
132 // Avoid loading editor-only CSS on the frontend.
133 if ( ! is_admin() ) {
134 return;
135 }
136
137 // Layout system CSS (shared variables and utilities)
138 $layout_css = __DIR__ . '/assets/css/layout.css';
139 if ( file_exists( $layout_css ) ) {
140 wp_enqueue_style(
141 'bkbg-layout-system',
142 plugins_url( 'assets/css/layout.css', __FILE__ ),
143 array(),
144 filemtime( $layout_css )
145 );
146 }
147
148 // Common editor styles for all blocks
149 $editor_css = __DIR__ . '/assets/css/editor.css';
150 if ( file_exists( $editor_css ) ) {
151 wp_enqueue_style(
152 'bkbg-editor-common',
153 plugins_url( 'assets/css/editor.css', __FILE__ ),
154 array( 'bkbg-layout-system' ),
155 filemtime( $editor_css )
156 );
157 }
158 } );
159
160 /**
161 * Register block scripts with dependencies (but don't enqueue them yet)
162 */
163 add_action( 'init', function () {
164 $blocks_dir = __DIR__ . '/blocks/';
165
166 // Standard WordPress script dependencies for blocks
167 $script_dependencies = array(
168 'wp-blocks',
169 'wp-element',
170 'wp-i18n',
171 'wp-block-editor',
172 'wp-components',
173 'wp-dom-ready',
174 'wp-data',
175 'bkbg-inspector-tabs',
176 'bkbg-typography-control',
177 'bkbg-icon-picker'
178 );
179
180 // Standard WordPress style dependencies for blocks
181 $style_dependencies = array(
182 'dashicons'
183 );
184
185 // Register layout system CSS for frontend
186 $layout_css = __DIR__ . '/assets/css/layout.css';
187 if ( file_exists( $layout_css ) ) {
188 wp_register_style(
189 'bkbg-layout-system',
190 plugins_url( 'assets/css/layout.css', __FILE__ ),
191 array(),
192 filemtime( $layout_css )
193 );
194 }
195
196 // Get disabled blocks list to skip asset registration.
197 $disabled_blocks = get_option( 'blockenberg_disabled_blocks', array() );
198 if ( ! is_array( $disabled_blocks ) ) {
199 $disabled_blocks = array();
200 }
201
202 // Automatically register scripts for all blocks
203 foreach ( glob( $blocks_dir . '*', GLOB_ONLYDIR ) as $block_dir ) {
204 $block_name = basename( $block_dir );
205
206 // Skip disabled blocks.
207 if ( in_array( 'blockenberg/' . $block_name, $disabled_blocks, true ) ) {
208 continue;
209 }
210
211 $script_file = $block_dir . '/index.js';
212
213 $style_file = $block_dir . '/style.css';
214 $frontend_file = $block_dir . '/frontend.js';
215
216 // Check if block has a JavaScript file
217 if ( file_exists( $script_file ) ) {
218 wp_register_script(
219 'bkbg-' . $block_name . '-editor',
220 plugins_url( 'blocks/' . $block_name . '/index.js', __FILE__ ),
221 $script_dependencies,
222 filemtime( $script_file ),
223 true
224 );
225 }
226
227 // Check if block has a CSS file
228 if ( file_exists( $style_file ) ) {
229 // Layout blocks need the layout system CSS
230 $block_style_deps = $style_dependencies;
231 if ( in_array( $block_name, array( 'section', 'row', 'column' ), true ) ) {
232 $block_style_deps[] = 'bkbg-layout-system';
233 }
234
235 wp_register_style(
236 'bkbg-' . $block_name . '-style',
237 plugins_url( 'blocks/' . $block_name . '/style.css', __FILE__ ),
238 $block_style_deps,
239 filemtime( $style_file )
240 );
241 }
242
243 // Check if block has a frontend JavaScript file
244 if ( file_exists( $frontend_file ) ) {
245 wp_register_script(
246 'bkbg-' . $block_name . '-frontend',
247 plugins_url( 'blocks/' . $block_name . '/frontend.js', __FILE__ ),
248 array( 'wp-dom-ready', 'bkbg-icon-picker-frontend' ),
249 filemtime( $frontend_file ),
250 true
251 );
252 }
253 }
254
255 // Automatically register all blocks in the /blocks directory
256 // Skip blocks the admin has disabled via the Blockenberg dashboard.
257 $disabled_blocks = get_option( 'blockenberg_disabled_blocks', array() );
258 if ( ! is_array( $disabled_blocks ) ) {
259 $disabled_blocks = array();
260 }
261
262 foreach ( glob( __DIR__ . '/blocks/*/block.json' ) as $metadata ) {
263 // Read block name from block.json to check against disabled list.
264 $raw_json = file_get_contents( $metadata );
265 $block_meta = $raw_json ? json_decode( $raw_json, true ) : null;
266 $block_name = is_array( $block_meta ) && isset( $block_meta['name'] ) ? $block_meta['name'] : '';
267
268 if ( '' !== $block_name && in_array( $block_name, $disabled_blocks, true ) ) {
269 continue; // Block is disabled — skip registration.
270 }
271
272 register_block_type( dirname( $metadata ) );
273 }
274 } );
275
276 // Register custom block category and ensure Blockenberg blocks appear in it.
277 add_filter( 'block_categories_all', function( $categories, $block_editor_context ) {
278 // Prepend Blockenberg sub-categories in reverse order so they appear in the right order.
279 $bkbg_categories = array(
280 array( 'slug' => 'blockenberg', 'title' => __( 'General (Blockenberg)', 'blockenberg' ), 'icon' => null ),
281 array( 'slug' => 'bkbg-layout', 'title' => __( 'Layout & Structure (Blockenberg)', 'blockenberg' ), 'icon' => null ),
282 array( 'slug' => 'bkbg-content', 'title' => __( 'Content & Typography (Blockenberg)', 'blockenberg' ), 'icon' => null ),
283 array( 'slug' => 'bkbg-media', 'title' => __( 'Media & Images (Blockenberg)', 'blockenberg' ), 'icon' => null ),
284 array( 'slug' => 'bkbg-marketing', 'title' => __( 'Marketing & Conversion (Blockenberg)','blockenberg' ), 'icon' => null ),
285 array( 'slug' => 'bkbg-business', 'title' => __( 'Business & Services (Blockenberg)', 'blockenberg' ), 'icon' => null ),
286 array( 'slug' => 'bkbg-blog', 'title' => __( 'Blog & Editorial (Blockenberg)', 'blockenberg' ), 'icon' => null ),
287 array( 'slug' => 'bkbg-interactive', 'title' => __( 'Interactive & Games (Blockenberg)', 'blockenberg' ), 'icon' => null ),
288 array( 'slug' => 'bkbg-charts', 'title' => __( 'Charts & Data (Blockenberg)', 'blockenberg' ), 'icon' => null ),
289 array( 'slug' => 'bkbg-calculators', 'title' => __( 'Calculators & Tools (Blockenberg)', 'blockenberg' ), 'icon' => null ),
290 array( 'slug' => 'bkbg-effects', 'title' => __( 'Effects & Animation (Blockenberg)', 'blockenberg' ), 'icon' => null ),
291 array( 'slug' => 'bkbg-dev', 'title' => __( 'Developer Tools (Blockenberg)', 'blockenberg' ), 'icon' => null ),
292 );
293 foreach ( array_reverse( $bkbg_categories ) as $cat ) {
294 array_unshift( $categories, $cat );
295 }
296 return $categories;
297 }, 10, 2 );
298
299 /**
300 * Load Google Fonts on the frontend for Blockenberg blocks.
301 * Scans block attributes for 'headerTypo', 'contentTypo', and any other
302 * attribute ending in 'Typo' that contains a non-empty 'family' key.
303 */
304 add_action( 'wp_enqueue_scripts', function () {
305 if ( ! is_singular() ) {
306 return;
307 }
308 $post = get_post();
309 if ( ! $post || ! has_blocks( $post->post_content ) ) {
310 return;
311 }
312
313 $system_fonts = array( 'Arial', 'Georgia', 'Helvetica', 'Tahoma', 'Times New Roman', 'Trebuchet MS', 'Verdana' );
314 $queued = array();
315
316 $blocks = parse_blocks( $post->post_content );
317
318 // Recursive walker for nested blocks
319 $collect = null;
320 $collect = function ( $blocks ) use ( &$collect, $system_fonts, &$queued ) {
321 foreach ( $blocks as $block ) {
322 if ( strpos( (string) $block['blockName'], 'blockenberg/' ) !== 0 ) {
323 if ( ! empty( $block['innerBlocks'] ) ) {
324 $collect( $block['innerBlocks'] );
325 }
326 continue;
327 }
328 $attrs = $block['attrs'] ?? array();
329 foreach ( $attrs as $key => $val ) {
330 // Any typography attribute (legacy *Typo suffix OR new typo* prefix)
331 // that is an array with a non-empty 'family' key.
332 $is_typo_key = ( substr( $key, -4 ) === 'Typo' ) || ( strpos( $key, 'typo' ) === 0 );
333 if ( $is_typo_key && is_array( $val ) && ! empty( $val['family'] ) ) {
334 $family = sanitize_text_field( $val['family'] );
335 if ( ! in_array( $family, $system_fonts, true ) && ! isset( $queued[ $family ] ) ) {
336 $queued[ $family ] = true;
337 $handle = 'bkbg-gf-' . sanitize_title( $family );
338 $url = 'https://fonts.googleapis.com/css2?family=' .
339 urlencode( $family ) .
340 ':wght@300;400;500;600;700;800;900&display=swap';
341 wp_enqueue_style( $handle, $url, array(), null );
342 }
343 }
344 }
345 if ( ! empty( $block['innerBlocks'] ) ) {
346 $collect( $block['innerBlocks'] );
347 }
348 }
349 };
350 $collect( $blocks );
351 } );
352
353 /**
354 * Register advanced layout attributes on the SERVER side for every Blockenberg block.
355 * Without this, WordPress strips unknown attributes during server-side parsing
356 * (array_intersect_key in WP_Block_Type::prepare_attributes_for_render).
357 */
358 add_filter( 'register_block_type_args', function ( $args, $block_type ) {
359 if ( strpos( $block_type, 'blockenberg/' ) !== 0 ) {
360 return $args;
361 }
362
363 // Blockenberg has its own Advanced spacing controls.
364 // Disable core Gutenberg "Dimensions" (spacing) UI to avoid duplicates.
365 if ( isset( $args['supports'] ) && is_array( $args['supports'] ) ) {
366 unset( $args['supports']['spacing'] );
367 unset( $args['supports']['__experimentalSpacing'] );
368 unset( $args['supports']['dimensions'] );
369 unset( $args['supports']['__experimentalDimensions'] );
370 }
371
372 $sides = array( 'Top', 'Right', 'Bottom', 'Left' );
373 $devices = array( '', 'Tablet', 'Mobile' );
374 $extra = array();
375
376 foreach ( array( 'bkbgMargin', 'bkbgPadding' ) as $prefix ) {
377 foreach ( $sides as $side ) {
378 foreach ( $devices as $device ) {
379 $key = $prefix . $side . $device;
380 $extra[ $key ] = array( 'type' => 'string', 'default' => '' );
381 $extra[ $key . 'Unit' ] = array( 'type' => 'string', 'default' => 'px' );
382 }
383 }
384 foreach ( $devices as $device ) {
385 $extra[ $prefix . 'Linked' . $device ] = array( 'type' => 'boolean', 'default' => true );
386 }
387 }
388
389 foreach ( $devices as $device ) {
390 $extra[ 'bkbgZIndex' . $device ] = array( 'type' => 'string', 'default' => '' );
391 }
392
393 $extra['bkbgCssId'] = array( 'type' => 'string', 'default' => '' );
394 $extra['bkbgCssClasses'] = array( 'type' => 'string', 'default' => '' );
395
396 // ── Background attributes ──
397 $extra['bkbgBgType'] = array( 'type' => 'string', 'default' => '' );
398 $extra['bkbgBgHoverType'] = array( 'type' => 'string', 'default' => '' );
399 $extra['bkbgBgColor'] = array( 'type' => 'string', 'default' => '' );
400 $extra['bkbgBgHoverColor']= array( 'type' => 'string', 'default' => '' );
401
402 // Classic image (responsive) — normal & hover
403 foreach ( array( 'bkbgBgImage', 'bkbgBgHoverImage' ) as $img_prefix ) {
404 foreach ( $devices as $device ) {
405 $extra[ $img_prefix . $device ] = array( 'type' => 'string', 'default' => '' );
406 $extra[ $img_prefix . 'Id' . $device ] = array( 'type' => 'number', 'default' => 0 );
407 }
408 }
409
410 // Classic image settings — normal & hover (position/repeat/size responsive, attachment global)
411 foreach ( array( 'bkbgBg', 'bkbgBgHover' ) as $s_prefix ) {
412 foreach ( $devices as $device ) {
413 $extra[ $s_prefix . 'Position' . $device ] = array( 'type' => 'string', 'default' => '' );
414 $extra[ $s_prefix . 'PositionCustomX' . $device ] = array( 'type' => 'string', 'default' => '' );
415 $extra[ $s_prefix . 'PositionCustomY' . $device ] = array( 'type' => 'string', 'default' => '' );
416 $extra[ $s_prefix . 'Repeat' . $device ] = array( 'type' => 'string', 'default' => '' );
417 $extra[ $s_prefix . 'Size' . $device ] = array( 'type' => 'string', 'default' => '' );
418 $extra[ $s_prefix . 'SizeCustomW' . $device ] = array( 'type' => 'string', 'default' => '' );
419 $extra[ $s_prefix . 'SizeCustomH' . $device ] = array( 'type' => 'string', 'default' => '' );
420 }
421 $extra[ $s_prefix . 'Attachment' ] = array( 'type' => 'string', 'default' => '' );
422 }
423
424 // Gradient — normal
425 $extra['bkbgBgGradColor1'] = array( 'type' => 'string', 'default' => '' );
426 $extra['bkbgBgGradColor2'] = array( 'type' => 'string', 'default' => '' );
427 $extra['bkbgBgGradType'] = array( 'type' => 'string', 'default' => 'linear' );
428 foreach ( $devices as $device ) {
429 $extra[ 'bkbgBgGradLoc1' . $device ] = array( 'type' => 'string', 'default' => '' );
430 $extra[ 'bkbgBgGradLoc2' . $device ] = array( 'type' => 'string', 'default' => '' );
431 $extra[ 'bkbgBgGradAngle' . $device ] = array( 'type' => 'string', 'default' => '' );
432 $extra[ 'bkbgBgGradPosition' . $device ] = array( 'type' => 'string', 'default' => '' );
433 }
434
435 // Gradient — hover
436 $extra['bkbgBgHoverGradColor1'] = array( 'type' => 'string', 'default' => '' );
437 $extra['bkbgBgHoverGradColor2'] = array( 'type' => 'string', 'default' => '' );
438 $extra['bkbgBgHoverGradType'] = array( 'type' => 'string', 'default' => 'linear' );
439 foreach ( $devices as $device ) {
440 $extra[ 'bkbgBgHoverGradLoc1' . $device ] = array( 'type' => 'string', 'default' => '' );
441 $extra[ 'bkbgBgHoverGradLoc2' . $device ] = array( 'type' => 'string', 'default' => '' );
442 $extra[ 'bkbgBgHoverGradAngle' . $device ] = array( 'type' => 'string', 'default' => '' );
443 $extra[ 'bkbgBgHoverGradPosition' . $device ] = array( 'type' => 'string', 'default' => '' );
444 }
445
446
447
448 // ── Border attributes ──
449
450 // Border Type (normal & hover)
451 $extra['bkbgBorderType'] = array( 'type' => 'string', 'default' => '' );
452 $extra['bkbgBorderHoverType'] = array( 'type' => 'string', 'default' => '' );
453
454 // Border Width — per side, per device, with unit (normal & hover)
455 foreach ( array( 'bkbgBorderWidth', 'bkbgBorderHoverWidth' ) as $prefix ) {
456 foreach ( $sides as $side ) {
457 foreach ( $devices as $device ) {
458 $key = $prefix . $side . $device;
459 $extra[ $key ] = array( 'type' => 'string', 'default' => '' );
460 $extra[ $key . 'Unit' ] = array( 'type' => 'string', 'default' => 'px' );
461 }
462 }
463 foreach ( $devices as $device ) {
464 $extra[ $prefix . 'Linked' . $device ] = array( 'type' => 'boolean', 'default' => true );
465 }
466 }
467
468 // Border Color (normal & hover)
469 $extra['bkbgBorderColor'] = array( 'type' => 'string', 'default' => '' );
470 $extra['bkbgBorderHoverColor'] = array( 'type' => 'string', 'default' => '' );
471
472 // Border Radius — per corner, per device, with unit (normal & hover)
473 foreach ( array( 'bkbgBorderRadius', 'bkbgBorderHoverRadius' ) as $prefix ) {
474 foreach ( $sides as $side ) {
475 foreach ( $devices as $device ) {
476 $key = $prefix . $side . $device;
477 $extra[ $key ] = array( 'type' => 'string', 'default' => '' );
478 $extra[ $key . 'Unit' ] = array( 'type' => 'string', 'default' => 'px' );
479 }
480 }
481 foreach ( $devices as $device ) {
482 $extra[ $prefix . 'Linked' . $device ] = array( 'type' => 'boolean', 'default' => true );
483 }
484 }
485
486 // Box Shadow (normal)
487 $extra['bkbgShadowColor'] = array( 'type' => 'string', 'default' => '' );
488 $extra['bkbgShadowH'] = array( 'type' => 'string', 'default' => '' );
489 $extra['bkbgShadowV'] = array( 'type' => 'string', 'default' => '' );
490 $extra['bkbgShadowBlur'] = array( 'type' => 'string', 'default' => '' );
491 $extra['bkbgShadowSpread'] = array( 'type' => 'string', 'default' => '' );
492 $extra['bkbgShadowPosition'] = array( 'type' => 'string', 'default' => '' );
493
494 // Box Shadow (hover)
495 $extra['bkbgShadowHoverColor'] = array( 'type' => 'string', 'default' => '' );
496 $extra['bkbgShadowHoverH'] = array( 'type' => 'string', 'default' => '' );
497 $extra['bkbgShadowHoverV'] = array( 'type' => 'string', 'default' => '' );
498 $extra['bkbgShadowHoverBlur'] = array( 'type' => 'string', 'default' => '' );
499 $extra['bkbgShadowHoverSpread'] = array( 'type' => 'string', 'default' => '' );
500 $extra['bkbgShadowHoverPosition'] = array( 'type' => 'string', 'default' => '' );
501
502
503 // Responsive visibility
504 $extra['bkbgHideDesktop'] = array( 'type' => 'boolean', 'default' => false );
505 $extra['bkbgHideTablet'] = array( 'type' => 'boolean', 'default' => false );
506 $extra['bkbgHideMobile'] = array( 'type' => 'boolean', 'default' => false );
507
508 if ( ! isset( $args['attributes'] ) || ! is_array( $args['attributes'] ) ) {
509 $args['attributes'] = array();
510 }
511 $args['attributes'] = array_merge( $args['attributes'], $extra );
512
513 return $args;
514 }, 10, 2 );
515
516 /**
517 * Render ALL advanced layout CSS (desktop + tablet + mobile) for Blockenberg blocks.
518 * Desktop styles are output as inline styles on the wrapper.
519 * Responsive styles use <style> tags with media queries.
520 * CSS ID / CSS Classes are also injected here for reliability.
521 */
522 add_filter( 'render_block', function ( $block_content, $block ) {
523 if ( empty( $block['blockName'] ) || strpos( $block['blockName'], 'blockenberg/' ) !== 0 ) {
524 return $block_content;
525 }
526
527 $attrs = $block['attrs'] ?? array();
528 if ( empty( $attrs ) ) {
529 return $block_content;
530 }
531
532 $sides = array( 'Top', 'Right', 'Bottom', 'Left' );
533 $devices = array( 'desktop', 'tablet', 'mobile' );
534
535 // Collect CSS rules per device
536 $css = array( 'desktop' => array(), 'tablet' => array(), 'mobile' => array() );
537
538 foreach ( array( 'bkbgMargin' => 'margin', 'bkbgPadding' => 'padding' ) as $prefix => $prop ) {
539 foreach ( $sides as $side ) {
540 foreach ( $devices as $dev ) {
541 $suffix = 'desktop' === $dev ? '' : ( 'tablet' === $dev ? 'Tablet' : 'Mobile' );
542 $val = isset( $attrs[ $prefix . $side . $suffix ] ) ? $attrs[ $prefix . $side . $suffix ] : '';
543 $unit = isset( $attrs[ $prefix . $side . $suffix . 'Unit' ] ) ? $attrs[ $prefix . $side . $suffix . 'Unit' ] : 'px';
544 if ( '' !== $val && '' !== trim( (string) $val ) ) {
545 $css[ $dev ][] = $prop . '-' . strtolower( $side ) . ':' . $val . $unit . ' !important';
546 }
547 }
548 }
549 }
550
551 // Z-Index per device
552 foreach ( $devices as $dev ) {
553 $suffix = 'desktop' === $dev ? '' : ( 'tablet' === $dev ? 'Tablet' : 'Mobile' );
554 $zi = isset( $attrs[ 'bkbgZIndex' . $suffix ] ) ? $attrs[ 'bkbgZIndex' . $suffix ] : '';
555 if ( '' !== $zi && '' !== trim( (string) $zi ) ) {
556 $css[ $dev ][] = 'z-index:' . intval( $zi );
557 $css[ $dev ][] = 'position:relative';
558 }
559 }
560
561 // ── Background CSS ──
562 $hover_css = array( 'desktop' => array(), 'tablet' => array(), 'mobile' => array() );
563
564 $bg_type = ! empty( $attrs['bkbgBgType'] ) ? $attrs['bkbgBgType'] : '';
565 $hover_type = ! empty( $attrs['bkbgBgHoverType'] ) ? $attrs['bkbgBgHoverType'] : '';
566
567 // Helper: build gradient value
568 $build_gradient = function ( $attrs, $prefix, $suffix ) {
569 $c1 = ! empty( $attrs[ $prefix . 'GradColor1' ] ) ? $attrs[ $prefix . 'GradColor1' ] : '';
570 $c2 = ! empty( $attrs[ $prefix . 'GradColor2' ] ) ? $attrs[ $prefix . 'GradColor2' ] : '';
571 if ( '' === $c1 && '' === $c2 ) return '';
572 if ( '' === $c1 ) $c1 = 'transparent';
573 if ( '' === $c2 ) $c2 = 'transparent';
574
575 // Location 1 — with fallback to desktop
576 $loc1 = '';
577 if ( '' !== $suffix && ! empty( $attrs[ $prefix . 'GradLoc1' . $suffix ] ) ) {
578 $loc1 = $attrs[ $prefix . 'GradLoc1' . $suffix ];
579 } elseif ( ! empty( $attrs[ $prefix . 'GradLoc1' ] ) ) {
580 $loc1 = $attrs[ $prefix . 'GradLoc1' ];
581 }
582
583 // Location 2
584 $loc2 = '';
585 if ( '' !== $suffix && ! empty( $attrs[ $prefix . 'GradLoc2' . $suffix ] ) ) {
586 $loc2 = $attrs[ $prefix . 'GradLoc2' . $suffix ];
587 } elseif ( ! empty( $attrs[ $prefix . 'GradLoc2' ] ) ) {
588 $loc2 = $attrs[ $prefix . 'GradLoc2' ];
589 }
590
591 // Angle
592 $angle = '';
593 if ( '' !== $suffix && isset( $attrs[ $prefix . 'GradAngle' . $suffix ] ) && '' !== $attrs[ $prefix . 'GradAngle' . $suffix ] ) {
594 $angle = $attrs[ $prefix . 'GradAngle' . $suffix ];
595 } elseif ( isset( $attrs[ $prefix . 'GradAngle' ] ) && '' !== $attrs[ $prefix . 'GradAngle' ] ) {
596 $angle = $attrs[ $prefix . 'GradAngle' ];
597 }
598
599 $type = ! empty( $attrs[ $prefix . 'GradType' ] ) ? $attrs[ $prefix . 'GradType' ] : 'linear';
600
601 $stop1 = esc_attr( $c1 ) . ( '' !== $loc1 ? ' ' . intval( $loc1 ) . '%' : '' );
602 $stop2 = esc_attr( $c2 ) . ( '' !== $loc2 ? ' ' . intval( $loc2 ) . '%' : '' );
603
604 if ( 'radial' === $type ) {
605 // Radial position
606 $pos = '';
607 if ( '' !== $suffix && ! empty( $attrs[ $prefix . 'GradPosition' . $suffix ] ) ) {
608 $pos = $attrs[ $prefix . 'GradPosition' . $suffix ];
609 } elseif ( ! empty( $attrs[ $prefix . 'GradPosition' ] ) ) {
610 $pos = $attrs[ $prefix . 'GradPosition' ];
611 }
612 $at_part = '' !== $pos ? ' at ' . esc_attr( $pos ) : '';
613 return 'radial-gradient(circle' . $at_part . ',' . $stop1 . ',' . $stop2 . ')';
614 }
615
616 $angle_part = '' !== $angle ? intval( $angle ) . 'deg,' : '';
617 return 'linear-gradient(' . $angle_part . $stop1 . ',' . $stop2 . ')';
618 };
619
620 // Helper: resolve responsive classic image settings (with desktop fallback)
621 $get_img_setting = function ( $attrs, $prefix, $prop, $suffix ) {
622 $val = ! empty( $attrs[ $prefix . $prop . $suffix ] ) ? $attrs[ $prefix . $prop . $suffix ] : '';
623 if ( '' === $val && '' !== $suffix ) {
624 $val = ! empty( $attrs[ $prefix . $prop ] ) ? $attrs[ $prefix . $prop ] : '';
625 }
626 return $val;
627 };
628
629 $render_classic_image_css = function ( $attrs, $prefix, &$target_css, $devices ) use ( $get_img_setting ) {
630 // Background color
631 if ( ! empty( $attrs[ $prefix . 'Color' ] ) ) {
632 $target_css['desktop'][] = 'background-color:' . esc_attr( $attrs[ $prefix . 'Color' ] ) . ' !important';
633 }
634 // Attachment (global, not responsive)
635 $attach = ! empty( $attrs[ $prefix . 'Attachment' ] ) ? esc_attr( $attrs[ $prefix . 'Attachment' ] ) : '';
636 if ( '' !== $attach ) {
637 $target_css['desktop'][] = 'background-attachment:' . $attach . ' !important';
638 }
639
640 foreach ( $devices as $dev ) {
641 $suffix = 'desktop' === $dev ? '' : ( 'tablet' === $dev ? 'Tablet' : 'Mobile' );
642 $img = ! empty( $attrs[ $prefix . 'Image' . $suffix ] ) ? $attrs[ $prefix . 'Image' . $suffix ] : '';
643 if ( '' === $img && '' !== $suffix ) {
644 $img = ! empty( $attrs[ $prefix . 'Image' ] ) ? $attrs[ $prefix . 'Image' ] : '';
645 }
646 if ( '' !== $img ) {
647 $target_css[ $dev ][] = 'background-image:url(' . esc_url( $img ) . ') !important';
648
649 // Position
650 $pos = $get_img_setting( $attrs, $prefix, 'Position', $suffix );
651 if ( 'custom' === $pos ) {
652 $cx = $get_img_setting( $attrs, $prefix, 'PositionCustomX', $suffix );
653 $cy = $get_img_setting( $attrs, $prefix, 'PositionCustomY', $suffix );
654 $cx = '' !== $cx ? intval( $cx ) . '%' : '50%';
655 $cy = '' !== $cy ? intval( $cy ) . '%' : '50%';
656 $target_css[ $dev ][] = 'background-position:' . $cx . ' ' . $cy . ' !important';
657 } elseif ( '' !== $pos ) {
658 $target_css[ $dev ][] = 'background-position:' . esc_attr( $pos ) . ' !important';
659 } else {
660 $target_css[ $dev ][] = 'background-position:center !important';
661 }
662
663 // Repeat
664 $repeat = $get_img_setting( $attrs, $prefix, 'Repeat', $suffix );
665 if ( '' !== $repeat ) {
666 $target_css[ $dev ][] = 'background-repeat:' . esc_attr( $repeat ) . ' !important';
667 }
668
669 // Size
670 $size = $get_img_setting( $attrs, $prefix, 'Size', $suffix );
671 if ( 'custom' === $size ) {
672 $sw = $get_img_setting( $attrs, $prefix, 'SizeCustomW', $suffix );
673 $sh = $get_img_setting( $attrs, $prefix, 'SizeCustomH', $suffix );
674 $sw = '' !== $sw ? intval( $sw ) . 'px' : 'auto';
675 $sh = '' !== $sh ? intval( $sh ) . 'px' : 'auto';
676 $target_css[ $dev ][] = 'background-size:' . $sw . ' ' . $sh . ' !important';
677 } elseif ( '' !== $size ) {
678 $target_css[ $dev ][] = 'background-size:' . esc_attr( $size ) . ' !important';
679 } else {
680 $target_css[ $dev ][] = 'background-size:cover !important';
681 }
682 }
683 }
684 };
685
686 // Normal — Classic
687 if ( 'classic' === $bg_type ) {
688 $render_classic_image_css( $attrs, 'bkbgBg', $css, $devices );
689 }
690
691 // Normal — Gradient
692 if ( 'gradient' === $bg_type ) {
693 foreach ( $devices as $dev ) {
694 $suffix = 'desktop' === $dev ? '' : ( 'tablet' === $dev ? 'Tablet' : 'Mobile' );
695 $grad = $build_gradient( $attrs, 'bkbgBg', $suffix );
696 if ( '' !== $grad ) {
697 $css[ $dev ][] = 'background-image:' . $grad . ' !important';
698 }
699 }
700 }
701
702 // Hover — Classic
703 if ( 'classic' === $hover_type ) {
704 $render_classic_image_css( $attrs, 'bkbgBgHover', $hover_css, $devices );
705 }
706
707 // Hover — Gradient
708 if ( 'gradient' === $hover_type ) {
709 foreach ( $devices as $dev ) {
710 $suffix = 'desktop' === $dev ? '' : ( 'tablet' === $dev ? 'Tablet' : 'Mobile' );
711 $grad = $build_gradient( $attrs, 'bkbgBgHover', $suffix );
712 if ( '' !== $grad ) {
713 $hover_css[ $dev ][] = 'background-image:' . $grad . ' !important';
714 }
715 }
716 }
717
718 // ── Border CSS ──
719
720 // Helper: build box-shadow value
721 $build_shadow = function ( $attrs, $prefix ) {
722 $h = isset( $attrs[ $prefix . 'H' ] ) && '' !== $attrs[ $prefix . 'H' ] ? intval( $attrs[ $prefix . 'H' ] ) : '';
723 $v = isset( $attrs[ $prefix . 'V' ] ) && '' !== $attrs[ $prefix . 'V' ] ? intval( $attrs[ $prefix . 'V' ] ) : '';
724 $blur = isset( $attrs[ $prefix . 'Blur' ] ) && '' !== $attrs[ $prefix . 'Blur' ] ? intval( $attrs[ $prefix . 'Blur' ] ) : '';
725 $spread = isset( $attrs[ $prefix . 'Spread' ] ) && '' !== $attrs[ $prefix . 'Spread' ] ? intval( $attrs[ $prefix . 'Spread' ] ) : '';
726 $color = ! empty( $attrs[ $prefix . 'Color' ] ) ? $attrs[ $prefix . 'Color' ] : '';
727 $pos = ! empty( $attrs[ $prefix . 'Position' ] ) ? $attrs[ $prefix . 'Position' ] : '';
728
729 if ( '' === $h && '' === $v && '' === $blur && '' === $spread && '' === $color ) return '';
730
731 $h = '' !== $h ? $h . 'px' : '0px';
732 $v = '' !== $v ? $v . 'px' : '0px';
733 $blur = '' !== $blur ? $blur . 'px' : '0px';
734 $spread = '' !== $spread ? $spread . 'px' : '0px';
735 $color = '' !== $color ? esc_attr( $color ) : 'rgba(0,0,0,0.5)';
736
737 $val = $h . ' ' . $v . ' ' . $blur . ' ' . $spread . ' ' . $color;
738 if ( 'inset' === $pos ) {
739 $val = 'inset ' . $val;
740 }
741 return $val;
742 };
743
744 // Helper: render border CSS for a prefix (normal or hover)
745 $render_border_css = function ( $attrs, $prefix_type, $prefix_width, $prefix_radius, $shadow_prefix, &$target_css, $devices ) use ( $build_shadow ) {
746 $border_type = ! empty( $attrs[ $prefix_type ] ) ? $attrs[ $prefix_type ] : '';
747
748 // Border type + width + color
749 if ( '' !== $border_type && 'none' !== $border_type ) {
750 $target_css['desktop'][] = 'border-style:' . esc_attr( $border_type ) . ' !important';
751
752 // Border color
753 $color_key = str_replace( 'Type', 'Color', $prefix_type );
754 if ( ! empty( $attrs[ $color_key ] ) ) {
755 $target_css['desktop'][] = 'border-color:' . esc_attr( $attrs[ $color_key ] ) . ' !important';
756 }
757
758 // Border width (responsive, per side)
759 foreach ( $devices as $dev ) {
760 $suffix = 'desktop' === $dev ? '' : ( 'tablet' === $dev ? 'Tablet' : 'Mobile' );
761 foreach ( array( 'Top', 'Right', 'Bottom', 'Left' ) as $side ) {
762 $val = isset( $attrs[ $prefix_width . $side . $suffix ] ) ? $attrs[ $prefix_width . $side . $suffix ] : '';
763 $unit = isset( $attrs[ $prefix_width . $side . $suffix . 'Unit' ] ) ? $attrs[ $prefix_width . $side . $suffix . 'Unit' ] : 'px';
764 if ( '' !== $val && '' !== trim( (string) $val ) ) {
765 $target_css[ $dev ][] = 'border-' . strtolower( $side ) . '-width:' . $val . $unit . ' !important';
766 }
767 }
768 }
769 } elseif ( 'none' === $border_type ) {
770 $target_css['desktop'][] = 'border:none !important';
771 }
772
773 // Border radius (responsive, per corner)
774 foreach ( $devices as $dev ) {
775 $suffix = 'desktop' === $dev ? '' : ( 'tablet' === $dev ? 'Tablet' : 'Mobile' );
776 $radius_parts = array();
777 foreach ( array( 'Top', 'Right', 'Bottom', 'Left' ) as $side ) {
778 $val = isset( $attrs[ $prefix_radius . $side . $suffix ] ) ? $attrs[ $prefix_radius . $side . $suffix ] : '';
779 $unit = isset( $attrs[ $prefix_radius . $side . $suffix . 'Unit' ] ) ? $attrs[ $prefix_radius . $side . $suffix . 'Unit' ] : 'px';
780 if ( '' !== $val && '' !== trim( (string) $val ) ) {
781 $radius_parts[ $side ] = $val . $unit;
782 }
783 }
784 if ( ! empty( $radius_parts ) ) {
785 // Map Top/Right/Bottom/Left to border-radius corners: TL TR BR BL
786 $tl = isset( $radius_parts['Top'] ) ? $radius_parts['Top'] : '0px';
787 $tr = isset( $radius_parts['Right'] ) ? $radius_parts['Right'] : '0px';
788 $br = isset( $radius_parts['Bottom'] ) ? $radius_parts['Bottom'] : '0px';
789 $bl = isset( $radius_parts['Left'] ) ? $radius_parts['Left'] : '0px';
790 $target_css[ $dev ][] = 'border-radius:' . $tl . ' ' . $tr . ' ' . $br . ' ' . $bl . ' !important';
791 }
792 }
793
794 // Box shadow
795 $shadow_val = $build_shadow( $attrs, $shadow_prefix );
796 if ( '' !== $shadow_val ) {
797 $target_css['desktop'][] = 'box-shadow:' . $shadow_val . ' !important';
798 }
799 };
800
801 // Normal border
802 $render_border_css( $attrs, 'bkbgBorderType', 'bkbgBorderWidth', 'bkbgBorderRadius', 'bkbgShadow', $css, $devices );
803
804 // Hover border
805 $render_border_css( $attrs, 'bkbgBorderHoverType', 'bkbgBorderHoverWidth', 'bkbgBorderHoverRadius', 'bkbgShadowHover', $hover_css, $devices );
806
807 // ── Responsive visibility ──
808 $hide_desktop = ! empty( $attrs['bkbgHideDesktop'] );
809 $hide_tablet = ! empty( $attrs['bkbgHideTablet'] );
810 $hide_mobile = ! empty( $attrs['bkbgHideMobile'] );
811
812 // Check if hover styles exist
813 $has_hover = ! empty( $hover_css['desktop'] ) || ! empty( $hover_css['tablet'] ) || ! empty( $hover_css['mobile'] );
814
815 // Any styles to output?
816 $has_responsive = $hide_desktop || $hide_tablet || $hide_mobile;
817 $has_styles = ! empty( $css['desktop'] ) || ! empty( $css['tablet'] ) || ! empty( $css['mobile'] ) || $has_hover || $has_responsive;
818 $has_id = ! empty( $attrs['bkbgCssId'] );
819 $has_cls = ! empty( $attrs['bkbgCssClasses'] );
820
821 if ( ! $has_styles && ! $has_id && ! $has_cls ) {
822 return $block_content;
823 }
824
825 // Generate a unique class for targeting this specific block instance
826 $unique = 'bkbg-adv-' . substr( md5( serialize( $attrs ) . wp_rand() ), 0, 8 );
827
828 // Inject unique class into the first HTML tag
829 $block_content = preg_replace(
830 '/(^\s*<[a-zA-Z][^>]*\bclass\s*=\s*")/',
831 '$1' . esc_attr( $unique ) . ' ',
832 $block_content,
833 1,
834 $count
835 );
836 if ( ! $count ) {
837 // No class attribute found — add one
838 $block_content = preg_replace(
839 '/(^\s*<[a-zA-Z][^\s>]*)/',
840 '$1 class="' . esc_attr( $unique ) . '"',
841 $block_content,
842 1
843 );
844 }
845
846 // Inject CSS ID
847 if ( $has_id ) {
848 $safe_id = esc_attr( $attrs['bkbgCssId'] );
849 $block_content = preg_replace(
850 '/(^\s*<[a-zA-Z][^>]*)/',
851 '$1 id="' . $safe_id . '"',
852 $block_content,
853 1
854 );
855 }
856
857 // Inject CSS Classes
858 if ( $has_cls ) {
859 $safe_cls = esc_attr( $attrs['bkbgCssClasses'] );
860 $block_content = preg_replace(
861 '/(^\s*<[a-zA-Z][^>]*\bclass\s*=\s*")/',
862 '$1' . $safe_cls . ' ',
863 $block_content,
864 1
865 );
866 }
867
868 // Build <style> tag
869 if ( $has_styles ) {
870 $sel = '.' . $unique;
871 $style = '';
872
873 if ( ! empty( $css['desktop'] ) ) {
874 $style .= $sel . '{' . implode( ';', $css['desktop'] ) . '}';
875 }
876 if ( ! empty( $css['tablet'] ) ) {
877 $style .= '@media(max-width:1024px){' . $sel . '{' . implode( ';', $css['tablet'] ) . '}}';
878 }
879 if ( ! empty( $css['mobile'] ) ) {
880 $style .= '@media(max-width:767px){' . $sel . '{' . implode( ';', $css['mobile'] ) . '}}';
881 }
882
883 // Hover rules
884 if ( ! empty( $hover_css['desktop'] ) ) {
885 $style .= $sel . ':hover{' . implode( ';', $hover_css['desktop'] ) . '}';
886 }
887 if ( ! empty( $hover_css['tablet'] ) ) {
888 $style .= '@media(max-width:1024px){' . $sel . ':hover{' . implode( ';', $hover_css['tablet'] ) . '}}';
889 }
890 if ( ! empty( $hover_css['mobile'] ) ) {
891 $style .= '@media(max-width:767px){' . $sel . ':hover{' . implode( ';', $hover_css['mobile'] ) . '}}';
892 }
893
894 // Responsive visibility: hide on specific devices
895 if ( $hide_desktop ) {
896 // Hide on desktop (>1024px)
897 $style .= '@media(min-width:1025px){' . $sel . '{display:none !important}}';
898 }
899 if ( $hide_tablet ) {
900 // Hide on tablet (768–1024px)
901 $style .= '@media(min-width:768px) and (max-width:1024px){' . $sel . '{display:none !important}}';
902 }
903 if ( $hide_mobile ) {
904 // Hide on mobile (≤767px)
905 $style .= '@media(max-width:767px){' . $sel . '{display:none !important}}';
906 }
907
908 $block_content .= '<style>' . $style . '</style>';
909 }
910
911 return $block_content;
912 }, 10, 2 );
913
914 /**
915 * Register REST API endpoint for Post Grid block.
916 *
917 * Route: /wp-json/blockenberg/v1/post-grid
918 * Method: GET
919 * Params:
920 * - type: string (posts|pages|any CPT)
921 * - orderby: string (date|title|comment_count|...)
922 * - order: string (asc|desc)
923 * - per_page: int
924 * - offset: int
925 * - page: int (1-based)
926 * - excerpt_len: int (optional)
927 */
928 add_action( 'rest_api_init', function () {
929 register_rest_route( 'blockenberg/v1', '/post-grid', array(
930 'methods' => 'GET',
931 'permission_callback' => '__return_true',
932 'args' => array(
933 'type' => array( 'sanitize_callback' => 'sanitize_key' ),
934 'orderby' => array( 'sanitize_callback' => 'sanitize_key' ),
935 'order' => array( 'sanitize_callback' => 'sanitize_text_field' ),
936 'per_page' => array( 'sanitize_callback' => 'absint' ),
937 'offset' => array( 'sanitize_callback' => 'absint' ),
938 'page' => array( 'sanitize_callback' => 'absint' ),
939 'excerpt_len' => array( 'sanitize_callback' => 'absint' ),
940 ),
941 'callback' => function ( WP_REST_Request $request ) {
942 $requested_type = sanitize_key( $request->get_param( 'type' ) ?: 'post' );
943 if ( 'posts' === $requested_type ) {
944 $requested_type = 'post';
945 } elseif ( 'pages' === $requested_type ) {
946 $requested_type = 'page';
947 }
948
949 $public_post_types = get_post_types( array( 'public' => true ), 'names' );
950 $post_type = in_array( $requested_type, $public_post_types, true ) ? $requested_type : 'post';
951
952 $requested_orderby = sanitize_key( $request->get_param( 'orderby' ) ?: 'date' );
953 $allowed_orderby = array( 'date', 'title', 'modified', 'comment_count', 'rand', 'menu_order' );
954 $orderby = in_array( $requested_orderby, $allowed_orderby, true ) ? $requested_orderby : 'date';
955 $order = strtolower( (string) $request->get_param( 'order' ) ) === 'asc' ? 'ASC' : 'DESC';
956 $per_page = max( 1, absint( $request->get_param( 'per_page' ) ?: 6 ) );
957 $per_page = min( 50, $per_page );
958 $offset = max( 0, absint( $request->get_param( 'offset' ) ?: 0 ) );
959 $offset = min( 5000, $offset );
960 $page = max( 1, absint( $request->get_param( 'page' ) ?: 1 ) );
961 $page = min( 200, $page );
962 $excerpt_len = max( 5, absint( $request->get_param( 'excerpt_len' ) ?: 18 ) );
963 $excerpt_len = min( 80, $excerpt_len );
964
965 // Short cache for public non-product queries.
966 $is_product_query = ( 'product' === $post_type );
967 $cache_key = '';
968 if ( ! $is_product_query ) {
969 $cache_key = 'bkbg_post_grid_' . md5( wp_json_encode( array(
970 'type' => $post_type,
971 'orderby' => $orderby,
972 'order' => $order,
973 'per_page' => $per_page,
974 'offset' => $offset,
975 'page' => $page,
976 'excerpt_len' => $excerpt_len,
977 ) ) );
978 $cached = get_transient( $cache_key );
979 if ( is_array( $cached ) ) {
980 return rest_ensure_response( $cached );
981 }
982 }
983
984 $q = new WP_Query( array(
985 'post_type' => $post_type,
986 'post_status' => 'publish',
987 'orderby' => $orderby,
988 'order' => $order,
989 'posts_per_page' => $per_page,
990 'offset' => $offset + ( ( $page - 1 ) * $per_page ),
991 'ignore_sticky_posts' => true,
992 'no_found_rows' => true,
993 ) );
994
995 $posts = array();
996 foreach ( $q->posts as $p ) {
997 $post_id = $p->ID;
998 $title = wp_strip_all_tags( get_the_title( $post_id ) );
999 $link = esc_url_raw( get_permalink( $post_id ) );
1000 $image = esc_url_raw( (string) get_the_post_thumbnail_url( $post_id, 'medium_large' ) );
1001 $date = wp_strip_all_tags( (string) get_the_date( '', $post_id ) );
1002 $author = sanitize_text_field( (string) get_the_author_meta( 'display_name', $p->post_author ) );
1003 $meta = trim( $date . ' · ' . $author );
1004 $raw = get_post_field( 'post_excerpt', $post_id );
1005 if ( '' === $raw ) {
1006 $raw = get_post_field( 'post_content', $post_id );
1007 }
1008 $excerpt = wp_strip_all_tags( wp_trim_words( wp_strip_all_tags( $raw ), $excerpt_len, '' ) );
1009
1010 $item = array(
1011 'id' => $post_id,
1012 'title' => $title,
1013 'link' => $link,
1014 'image' => $image,
1015 'meta' => $meta,
1016 'excerpt' => $excerpt,
1017 );
1018
1019 if ( 'product' === $post_type && function_exists( 'wc_get_product' ) ) {
1020 $product = wc_get_product( $post_id );
1021 if ( $product ) {
1022 $item['price_html'] = wp_kses_post( $product->get_price_html() );
1023 $item['add_to_cart'] = esc_url_raw( $product->add_to_cart_url() );
1024 }
1025 }
1026
1027 $posts[] = $item;
1028 }
1029
1030 $payload = array( 'posts' => $posts );
1031
1032 if ( ! $is_product_query && '' !== $cache_key ) {
1033 set_transient( $cache_key, $payload, 60 );
1034 }
1035
1036 return rest_ensure_response( $payload );
1037 },
1038 ) );
1039 } );
1040
1041 /**
1042 * Simple local newsletter subscribe endpoint.
1043 * Stores emails in an option array; extend as needed (e.g., to a custom table).
1044 */
1045 add_action( 'rest_api_init', function () {
1046 register_rest_route( 'blockenberg/v1', '/subscribe', array(
1047 'methods' => 'POST',
1048 'permission_callback' => '__return_true',
1049 'args' => array(
1050 'email' => array( 'sanitize_callback' => 'sanitize_email' ),
1051 'website' => array( 'sanitize_callback' => 'sanitize_text_field' ),
1052 ),
1053 'callback' => function ( WP_REST_Request $request ) {
1054 $payload = $request->get_json_params();
1055 if ( ! is_array( $payload ) ) {
1056 $payload = array();
1057 }
1058
1059 // Basic rate limiting by IP to reduce spam / abuse.
1060 $ip = '';
1061 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
1062 $ip = sanitize_text_field( wp_unslash( (string) $_SERVER['REMOTE_ADDR'] ) );
1063 }
1064 if ( '' !== $ip ) {
1065 $key = 'bkbg_subscribe_' . md5( $ip );
1066 $rl = get_transient( $key );
1067 if ( is_array( $rl ) && isset( $rl['count'], $rl['start'] ) ) {
1068 if ( $rl['count'] >= 5 ) {
1069 return new WP_Error( 'rate_limited', __( 'Too many requests. Please try again later.', 'blockenberg' ), array( 'status' => 429 ) );
1070 }
1071 $rl['count']++;
1072 set_transient( $key, $rl, 60 );
1073 } else {
1074 set_transient( $key, array( 'count' => 1, 'start' => time() ), 60 );
1075 }
1076 }
1077
1078 // Optional honeypot field (bots tend to fill it).
1079 $honeypot = isset( $payload['website'] ) ? sanitize_text_field( (string) $payload['website'] ) : '';
1080 if ( '' !== $honeypot ) {
1081 return rest_ensure_response( array( 'ok' => true ) );
1082 }
1083
1084 $email = isset( $payload['email'] ) ? sanitize_email( (string) $payload['email'] ) : '';
1085 if ( empty( $email ) || ! is_email( $email ) ) {
1086 return new WP_Error( 'invalid_email', __( 'Invalid email address', 'blockenberg' ), array( 'status' => 400 ) );
1087 }
1088
1089 $list = get_option( 'blockenberg_newsletter_subscribers', array() );
1090 if ( ! is_array( $list ) ) {
1091 $list = array();
1092 }
1093
1094 // Prevent unbounded option growth.
1095 if ( count( $list ) >= 5000 ) {
1096 return new WP_Error( 'storage_full', __( 'Subscriber list is full.', 'blockenberg' ), array( 'status' => 503 ) );
1097 }
1098
1099 if ( ! in_array( $email, $list, true ) ) {
1100 $list[] = $email;
1101 update_option( 'blockenberg_newsletter_subscribers', $list, false );
1102 }
1103 return rest_ensure_response( array( 'ok' => true ) );
1104 },
1105 ) );
1106 } );
1107
1108 /**
1109 * Strip CR/LF and related sequences so values cannot inject mail headers.
1110 *
1111 * @param string $value Raw header fragment.
1112 * @return string
1113 */
1114 function bkbg_sanitize_mail_header( $value ) {
1115 $value = (string) $value;
1116 $value = str_replace( array( "\r", "\n", '%0a', '%0d', '%0A', '%0D' ), '', $value );
1117 return trim( sanitize_text_field( $value ) );
1118 }
1119
1120 /**
1121 * HMAC signature for a contact-form recipient email.
1122 * Prevents open-relay abuse: the client may only use a recipient that was
1123 * signed server-side when the block was rendered.
1124 *
1125 * @param string $email Recipient email.
1126 * @return string Hex HMAC or empty string if invalid.
1127 */
1128 function bkbg_contact_recipient_sig( $email ) {
1129 $email = strtolower( sanitize_email( (string) $email ) );
1130 if ( ! is_email( $email ) ) {
1131 return '';
1132 }
1133 return hash_hmac( 'sha256', $email, wp_salt( 'auth' ) );
1134 }
1135
1136 /**
1137 * Verify a contact-form recipient signature.
1138 *
1139 * @param string $email Recipient email from the client.
1140 * @param string $sig HMAC from data-recipient-sig.
1141 * @return bool
1142 */
1143 function bkbg_verify_contact_recipient( $email, $sig ) {
1144 $email = strtolower( sanitize_email( (string) $email ) );
1145 if ( ! is_email( $email ) || ! is_string( $sig ) || '' === $sig ) {
1146 return false;
1147 }
1148 $expected = bkbg_contact_recipient_sig( $email );
1149 return ( '' !== $expected && hash_equals( $expected, $sig ) );
1150 }
1151
1152 /**
1153 * Inject a server-signed recipient HMAC into Contact Form markup on render.
1154 * Existing posts do not need to be re-saved — the signature is added at runtime.
1155 */
1156 add_filter( 'render_block', function ( $block_content, $block ) {
1157 if ( empty( $block['blockName'] ) || 'blockenberg/contact-form' !== $block['blockName'] ) {
1158 return $block_content;
1159 }
1160 if ( ! is_string( $block_content ) || '' === $block_content ) {
1161 return $block_content;
1162 }
1163
1164 $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array();
1165 $recipient = isset( $attrs['recipientEmail'] ) ? sanitize_email( (string) $attrs['recipientEmail'] ) : '';
1166 if ( ! is_email( $recipient ) ) {
1167 return $block_content;
1168 }
1169
1170 $sig = bkbg_contact_recipient_sig( $recipient );
1171 if ( '' === $sig ) {
1172 return $block_content;
1173 }
1174
1175 // Replace existing sig if present, otherwise inject onto the first opening tag.
1176 if ( false !== strpos( $block_content, 'data-recipient-sig=' ) ) {
1177 $block_content = preg_replace(
1178 '/\sdata-recipient-sig=(["\'])[^"\']*\1/',
1179 ' data-recipient-sig="' . esc_attr( $sig ) . '"',
1180 $block_content,
1181 1
1182 );
1183 } else {
1184 $block_content = preg_replace(
1185 '/^\s*(<[a-zA-Z][^>]*)/',
1186 '$1 data-recipient-sig="' . esc_attr( $sig ) . '"',
1187 $block_content,
1188 1
1189 );
1190 }
1191
1192 return $block_content;
1193 }, 10, 2 );
1194
1195 /**
1196 * Contact Form endpoint — POST /wp-json/blockenberg/v1/contact
1197 * Sends an email via wp_mail() to the admin or a custom recipient stored in the block.
1198 * Custom recipients require a valid server-issued HMAC (data-recipient-sig).
1199 */
1200 add_action( 'rest_api_init', function () {
1201 register_rest_route( 'blockenberg/v1', '/contact', array(
1202 'methods' => 'POST',
1203 'permission_callback' => '__return_true',
1204 'callback' => function ( WP_REST_Request $request ) {
1205 $payload = $request->get_json_params();
1206 if ( ! is_array( $payload ) ) {
1207 $payload = array();
1208 }
1209
1210 // Rate-limit by IP: max 5 requests per 60 s.
1211 $ip = '';
1212 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
1213 $ip = sanitize_text_field( wp_unslash( (string) $_SERVER['REMOTE_ADDR'] ) );
1214 }
1215 if ( '' !== $ip ) {
1216 $rl_key = 'bkbg_contact_' . md5( $ip );
1217 $rl = get_transient( $rl_key );
1218 if ( is_array( $rl ) && isset( $rl['count'] ) && $rl['count'] >= 5 ) {
1219 return new WP_Error( 'rate_limited', __( 'Too many requests. Please try again later.', 'blockenberg' ), array( 'status' => 429 ) );
1220 }
1221 if ( is_array( $rl ) ) {
1222 $rl['count']++;
1223 set_transient( $rl_key, $rl, 60 );
1224 } else {
1225 set_transient( $rl_key, array( 'count' => 1 ), 60 );
1226 }
1227 }
1228
1229 // Honeypot check (bots fill the hidden website field).
1230 $honeypot = isset( $payload['website'] ) ? sanitize_text_field( (string) $payload['website'] ) : '';
1231 if ( '' !== $honeypot ) {
1232 return rest_ensure_response( array( 'ok' => true ) ); // silently accept.
1233 }
1234
1235 // Validate required fields.
1236 $name = isset( $payload['name'] ) ? sanitize_text_field( (string) $payload['name'] ) : '';
1237 $email = isset( $payload['email'] ) ? sanitize_email( (string) $payload['email'] ) : '';
1238 $phone = isset( $payload['phone'] ) ? sanitize_text_field( (string) $payload['phone'] ) : '';
1239 $message = isset( $payload['message'] ) ? sanitize_textarea_field( (string) $payload['message'] ) : '';
1240
1241 if ( ! is_email( $email ) ) {
1242 return new WP_Error( 'invalid_email', __( 'Invalid email address.', 'blockenberg' ), array( 'status' => 400 ) );
1243 }
1244 if ( empty( $message ) ) {
1245 return new WP_Error( 'empty_message', __( 'Message is required.', 'blockenberg' ), array( 'status' => 400 ) );
1246 }
1247
1248 // Recipient: only accept a client-supplied address when it carries a
1249 // valid server HMAC. Otherwise always fall back to admin_email (no open relay).
1250 $admin_email = sanitize_email( (string) get_option( 'admin_email' ) );
1251 $recipient = $admin_email;
1252 $requested = isset( $payload['recipient'] ) ? sanitize_email( (string) $payload['recipient'] ) : '';
1253 $sig = isset( $payload['recipientSig'] ) ? (string) $payload['recipientSig'] : '';
1254 if ( is_email( $requested ) && bkbg_verify_contact_recipient( $requested, $sig ) ) {
1255 $recipient = strtolower( $requested );
1256 }
1257
1258 $subject = isset( $payload['subject'] ) ? bkbg_sanitize_mail_header( (string) $payload['subject'] ) : '';
1259 if ( '' === $subject ) {
1260 $subject = __( 'New Contact Form Submission', 'blockenberg' );
1261 }
1262
1263 // Build email body.
1264 $body = "Name: {$name}\n";
1265 $body .= "Email: {$email}\n";
1266 if ( ! empty( $phone ) ) {
1267 $body .= "Phone: {$phone}\n";
1268 }
1269 $body .= "\nMessage:\n{$message}\n";
1270
1271 // Reply-To: strip CR/LF from name; never allow header injection.
1272 $safe_name = bkbg_sanitize_mail_header( $name );
1273 $safe_name = str_replace( array( '"', '<', '>' ), '', $safe_name );
1274 if ( '' !== $safe_name ) {
1275 $reply_to = sprintf( 'Reply-To: %s <%s>', $safe_name, $email );
1276 } else {
1277 $reply_to = 'Reply-To: ' . $email;
1278 }
1279
1280 $headers = array(
1281 'Content-Type: text/plain; charset=UTF-8',
1282 $reply_to,
1283 );
1284
1285 $sent = wp_mail( $recipient, $subject, $body, $headers );
1286
1287 if ( ! $sent ) {
1288 return new WP_Error( 'mail_failed', __( 'Failed to send email. Please try again.', 'blockenberg' ), array( 'status' => 500 ) );
1289 }
1290
1291 return rest_ensure_response( array( 'ok' => true ) );
1292 },
1293 ) );
1294 } );
1295