83 lines
2.5 KiB
PHP
83 lines
2.5 KiB
PHP
<?php
|
|
function render_bar_graph_block($attributes, $content) {
|
|
// Ensure all required attributes have default values
|
|
$defaults = array(
|
|
'chartHeight' => 400,
|
|
'chartWidth' => 600,
|
|
'barColor' => '#FF6384',
|
|
'barOpacity' => 0.8,
|
|
'backgroundColor' => '#FFFFFF',
|
|
'showGridY' => true,
|
|
'showGridX' => true,
|
|
'yGridColor' => '#e0e0e0',
|
|
'xGridColor' => '#e0e0e0',
|
|
'xGridWidth' => 1,
|
|
'yGridWidth' => 1,
|
|
'chartData' => array(),
|
|
'displayChartTitle' => false,
|
|
'chartTitle' => '',
|
|
'showBarValues' => false,
|
|
'xAxisLabel' => '',
|
|
'yAxisLabel' => '',
|
|
'chartColorSource' => 'default',
|
|
'chartCustomColors' => array()
|
|
);
|
|
|
|
// Merge provided attributes with defaults
|
|
$attributes = wp_parse_args($attributes, $defaults);
|
|
|
|
// If chartData is a string (JSON), decode it
|
|
if (is_string($attributes['chartData'])) {
|
|
$attributes['chartData'] = json_decode($attributes['chartData'], true);
|
|
}
|
|
|
|
// If chartCustomColors is a string (JSON), decode it
|
|
if (is_string($attributes['chartCustomColors'])) {
|
|
$attributes['chartCustomColors'] = json_decode($attributes['chartCustomColors'], true);
|
|
}
|
|
|
|
// Create a unique ID for this instance of the graph
|
|
$block_id = 'bar-graph-' . uniqid();
|
|
|
|
// Prepare the data for JavaScript
|
|
$js_data = array(
|
|
'attributes' => $attributes,
|
|
'blockId' => $block_id
|
|
);
|
|
|
|
// Enqueue D3.js if not already enqueued
|
|
wp_enqueue_script(
|
|
'lcp-d3',
|
|
'https://d3js.org/d3.v7.min.js',
|
|
array(),
|
|
'7.0.0',
|
|
true
|
|
);
|
|
|
|
// Enqueue the view script if not already enqueued
|
|
wp_enqueue_script(
|
|
'lcp-bar-graph-view',
|
|
plugins_url('build/view.js', __FILE__),
|
|
array('lcp-d3'),
|
|
filemtime(plugin_dir_path(__FILE__) . 'build/view.js'),
|
|
true
|
|
);
|
|
|
|
// Pass the data to JavaScript
|
|
wp_add_inline_script(
|
|
'lcp-bar-graph-view',
|
|
'window.lcpBarGraphData = window.lcpBarGraphData || {};' .
|
|
'window.lcpBarGraphData["' . $block_id . '"] = ' . wp_json_encode($js_data) . ';',
|
|
'before'
|
|
);
|
|
|
|
// Return the container for the graph
|
|
return sprintf(
|
|
'<div class="wp-block-lcp-bar-graph" id="%s">
|
|
<div class="bar-graph-container" style="min-height:%dpx"></div>
|
|
</div>',
|
|
esc_attr($block_id),
|
|
esc_attr($attributes['chartHeight'])
|
|
);
|
|
}
|