April 5, 2024 at 11:39 pm
#1439304
Hey marco593,
Thank you for your patience, the following javascript will add the chart title to the center of the Doughnut Chart,
If you are not using a child theme you could use the WP Code plugin then add a new snippet, in the top right corner use the PHP snippet as the code type:
then add this code and save.
function doughnut_chart_with_title_in_center() { ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
function waitForChartJs() {
if (typeof Chart === 'undefined') {
setTimeout(waitForChartJs, 50);
} else {
registerCenterTitlePlugin();
}
}
function registerCenterTitlePlugin() {
Chart.register({
id: 'centerTitle',
beforeInit: function(chart) {
// Dynamically hide the title and legend
const options = chart.options;
if (options.plugins) {
if (!options.plugins.title) {
options.plugins.title = {};
}
options.plugins.title.display = false; // Hide title
if (!options.plugins.legend) {
options.plugins.legend = {};
}
options.plugins.legend.display = false; // Hide legend
}
},
afterDraw: function(chart) {
if (chart.config.type === 'doughnut') {
const ctx = chart.ctx;
const width = chart.width;
const height = chart.height;
const fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
// Use existing title if set, otherwise use a default text
const text = chart.options.plugins.title.text || 'Your Title Here';
const textX = width / 2;
const textY = height / 2;
ctx.fillText(text, textX, textY);
}
}
});
}
waitForChartJs();
});
</script>
<?php
}
add_action( 'wp_footer', 'doughnut_chart_with_title_in_center', 99 );
Best regards,
Mike