chart.js 이용해서 테이블 값을 그래프로 표현하는 코드임
바, 선, 원형 등 다양한 그래프로 표현 가능함
| 월 | 매출액 (만원) |
|---|---|
| 1월 | 250 |
| 2월 | 320 |
| 3월 | 280 |
| 4월 | 450 |
| 5월 | 390 |
예를들어 1월-12월까지 매출을 입력하면 그래프로 표기되는걸 만든다고 하면,
ACF 이용해서 포스트1-12로 입력값 받으면 그걸 테이블로 표기하고 그래프로 나타낼 수 있음
PHP: WordPress 루프를 돌려 1-12월까지의 매출액을 담은 HTML 테이블을 생성합니다.
JavaScript: 페이지 로드 후, 이미 만들어진 HTML 테이블의 데이터를 읽어와 그 값으로 그래프를 그립니다.
<div style="display: flex; gap: 50px; justify-content: center;">
<table id="dataTable">
<thead>
<tr>
<th>월</th>
<th>매출액</th>
</tr>
</thead>
<tbody>
<?php
// WP_Query를 사용하여 12개의 포스트를 불러옵니다.
$args = array(
'post_type' => 'sales_data', // 커스텀 포스트 타입명
'posts_per_page' => 12,
'orderby' => 'date',
'order' => 'ASC'
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$month = get_field('month');
$amount = get_field('sales_amount');
if ($month && $amount) {
echo '<tr>';
echo '<td>' . esc_html($month) . '</td>';
echo '<td>' . esc_html($amount) . '</td>';
echo '</tr>';
}
}
wp_reset_postdata();
}
?>
</tbody>
</table>
<canvas id="myChart" width="500" height="400"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
document.addEventListener("DOMContentLoaded", () => {
// 1. HTML 요소 가져오기
const table = document.getElementById('dataTable');
const myChart = document.getElementById('myChart');
let labels = []; // 월 (레이블)
let dataValues = []; // 매출액 (데이터)
// 2. 테이블 데이터 추출하기
const rows = table.querySelectorAll('tbody tr');
rows.forEach(row => {
const cells = row.querySelectorAll('td');
if (cells.length > 1) {
labels.push(cells[0].textContent); // 첫 번째 셀 (월)
dataValues.push(parseInt(cells[1].textContent.replace(/,/g, ''))); // 두 번째 셀 (매출액)
}
});
// 3. Chart.js 설정 및 그리기
const data = {
labels: labels, // 테이블에서 추출한 월
datasets: [{
label: '월별 매출액',
data: dataValues, // 테이블에서 추출한 매출액
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
};
const config = {
type: 'bar', // 막대 그래프
data: data,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
};
new Chart(myChart, config);
});
