Chartjs
Omschrijving
Simple yet flexible JavaScript charting library for the modern web.
Voorbeeld
To add the Chart.js library to your plugin and create a Line Chart to compare data from different weeks, follow these steps:
- Include Chart.js Library: Enqueue the Chart.js library in your plugin.
- Create a Container for the Chart: Add a canvas element where the chart will be rendered.
- Fetch and Prepare Data: Retrieve the data for different weeks and prepare it for the chart.
- Initialize the Chart: Use JavaScript to initialize the Chart.js Line Chart with the prepared data.
Here is the step-by-step implementation:
Step 1: Enqueue Chart.js Library
Add the following code to enqueue the Chart.js library in your plugin’s main PHP file:
function enqueue_chart_js() {
wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_chart_js');Step 2: Create a Container for the Chart
Add a canvas element in your kpis.php file where the chart will be rendered:
<div class="chart-container" style="position: relative; height:40vh; width:80vw">
<canvas id="weekComparisonChart"></canvas>
</div>Step 3: Fetch and Prepare Data
Add a PHP block to fetch the data for different weeks and pass it to JavaScript:
<?php
// Fetch data for different weeks
$weeks_data = array();
$weeks = get_posts(array(
'post_type' => 'report',
'meta_key' => 'report_type',
'meta_value' => 'KPI',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'ASC'
));
foreach ($weeks as $week) {
$week_number = get_field('report_week', $week->ID);
$calories = get_field('report_kpi_week_total_calories', $week->ID);
$weeks_data[] = array(
'week' => $week_number,
'calories' => $calories
);
}
?>
<script>
var weeksData = <?php echo json_encode($weeks_data); ?>;
</script>Step 4: Initialize the Chart
Add the following JavaScript code to initialize the Chart.js Line Chart:
<script>
document.addEventListener('DOMContentLoaded', function() {
var ctx = document.getElementById('weekComparisonChart').getContext('2d');
var labels = weeksData.map(function(data) { return 'Week ' + data.week; });
var data = weeksData.map(function(data) { return data.calories; });
var weekComparisonChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Calories per Week',
data: data,
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
fill: true
}]
},
options: {
responsive: true,
scales: {
x: {
title: {
display: true,
text: 'Week'
}
},
y: {
title: {
display: true,
text: 'Calories'
}
}
}
}
});
});
</script>This code will render a Line Chart comparing the calories data from different weeks. Make sure to adjust the data fetching logic as per your requirements.
Relations
| Item | Type |
|---|
Pointing items
| Item | Type | Category | Tags |
|---|
| Categorie | Library |
| Tags | chart, charts, Javascript, library |
| URL | https://www.chartjs.org/ |
| Type | Library |
| Time | |
| Price |