75 lines
2.1 KiB
PHP
75 lines
2.1 KiB
PHP
<?php
|
|
/**
|
|
* Bar Graph Block Registration
|
|
*
|
|
* @package LCP-Data-Blocks
|
|
*/
|
|
|
|
if (!defined('ABSPATH')) {
|
|
exit; // Exit if accessed directly.
|
|
}
|
|
|
|
/**
|
|
* Registers the block using the metadata loaded from the `block.json` file.
|
|
*/
|
|
function lcp_bar_graph_block_init() {
|
|
// Register the block using the metadata loaded from the `block.json` file.
|
|
register_block_type(
|
|
__DIR__ . '/build',
|
|
array(
|
|
'render_callback' => 'lcp_render_bar_graph_block'
|
|
)
|
|
);
|
|
}
|
|
add_action('init', 'lcp_bar_graph_block_init');
|
|
|
|
/**
|
|
* Register D3.js as a dependency
|
|
*/
|
|
function lcp_register_d3() {
|
|
wp_register_script(
|
|
'd3',
|
|
'https://d3js.org/d3.v7.min.js',
|
|
array(),
|
|
'7.0.0',
|
|
true
|
|
);
|
|
}
|
|
add_action('wp_enqueue_scripts', 'lcp_register_d3');
|
|
add_action('enqueue_block_editor_assets', 'lcp_register_d3');
|
|
|
|
/**
|
|
* Renders the block on the server.
|
|
*
|
|
* @param array $attributes Block attributes.
|
|
* @param string $content Block default content.
|
|
* @return string Returns the block content.
|
|
*/
|
|
function lcp_render_bar_graph_block($attributes, $content) {
|
|
if (!is_array($attributes)) {
|
|
$attributes = array();
|
|
}
|
|
|
|
// Get attributes with defaults
|
|
$chart_height = $attributes['chartHeight'] ?? '400px';
|
|
$background_color = $attributes['backgroundColor'] ?? '#ffffff';
|
|
$bar_color = $attributes['barColor'] ?? '#0073aa';
|
|
$bar_opacity = $attributes['barOpacity'] ?? 1;
|
|
$show_grid_y = $attributes['showGridY'] ?? true;
|
|
$grid_color = $attributes['gridColor'] ?? '#e0e0e0';
|
|
|
|
// Enqueue D3.js
|
|
wp_enqueue_script('d3');
|
|
|
|
// Return the block's container
|
|
return sprintf(
|
|
'<div class="wp-block-lcp-bar-graph"><div class="lcp-bar-graph" style="height: %s; background-color: %s;" data-bar-color="%s" data-bar-opacity="%f" data-show-grid="%s" data-grid-color="%s"></div></div>',
|
|
esc_attr($chart_height),
|
|
esc_attr($background_color),
|
|
esc_attr($bar_color),
|
|
esc_attr($bar_opacity),
|
|
esc_attr($show_grid_y ? 'true' : 'false'),
|
|
esc_attr($grid_color)
|
|
);
|
|
}
|