| 1 |
<?php |
| 2 |
if ( ! defined( 'ABSPATH' ) ) exit; |
| 3 |
|
| 4 |
/** |
| 5 |
* Register the Contact Forms block for the block editor. |
| 6 |
*/ |
| 7 |
function accua_forms_register_block() { |
| 8 |
if ( ! function_exists( 'register_block_type' ) ) { |
| 9 |
return; |
| 10 |
} |
| 11 |
|
| 12 |
wp_register_script( |
| 13 |
'contact-forms-block-editor', |
| 14 |
plugins_url( 'block-editor/index.js', ACCUA_FORMS_FILE ), |
| 15 |
array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-block-editor', 'wp-i18n', 'wp-server-side-render' ), |
| 16 |
ACCUA_FORMS_JS_VERSION, |
| 17 |
true |
| 18 |
); |
| 19 |
|
| 20 |
wp_set_script_translations( 'contact-forms-block-editor', 'contact-forms', plugin_dir_path( ACCUA_FORMS_FILE ) . 'languages' ); |
| 21 |
|
| 22 |
// Pass form list to the block editor script |
| 23 |
$forms = get_option( 'accua_forms_saved_forms', array() ); |
| 24 |
$form_list = array(); |
| 25 |
foreach ( $forms as $fid => $form_data ) { |
| 26 |
$title = ! empty( $form_data['title'] ) ? $form_data['title'] : __( '(untitled)', 'contact-forms' ); |
| 27 |
$form_list[] = array( |
| 28 |
'text' => $title, |
| 29 |
'value' => (string) $fid, |
| 30 |
); |
| 31 |
} |
| 32 |
usort( $form_list, function( $a, $b ) { |
| 33 |
return (int) $b['value'] - (int) $a['value']; |
| 34 |
} ); |
| 35 |
|
| 36 |
wp_add_inline_script( |
| 37 |
'contact-forms-block-editor', |
| 38 |
'var accua_forms_block_data = ' . wp_json_encode( array( 'forms' => $form_list ) ) . ';', |
| 39 |
'before' |
| 40 |
); |
| 41 |
|
| 42 |
// The "render" property of block.json is only honored from WordPress 6.1, |
| 43 |
// so on 5.9/6.0 (still supported per "Requires at least") the block would |
| 44 |
// register without a render callback and output nothing on the front end. |
| 45 |
// Passing the callback explicitly covers those versions; on 6.1+ the |
| 46 |
// explicit argument wins over the one derived from the metadata, and both |
| 47 |
// resolve to the same render.php. |
| 48 |
register_block_type( |
| 49 |
plugin_dir_path( ACCUA_FORMS_FILE ) . 'block-editor', |
| 50 |
array( 'render_callback' => 'accua_forms_render_block' ) |
| 51 |
); |
| 52 |
} |
| 53 |
add_action( 'init', 'accua_forms_register_block' ); |
| 54 |
|
| 55 |
/** |
| 56 |
* Render the Contact Form block. |
| 57 |
* |
| 58 |
* @param array $attributes Block attributes (formId). |
| 59 |
* @return string The rendered form markup, or an empty string. |
| 60 |
*/ |
| 61 |
function accua_forms_render_block( $attributes ) { |
| 62 |
ob_start(); |
| 63 |
include plugin_dir_path( ACCUA_FORMS_FILE ) . 'block-editor/render.php'; |
| 64 |
return ob_get_clean(); |
| 65 |
} |
| 66 |
|