以下に、外部APIからデータを取得し、WordPressに統合してチャートを表示する方法を詳しく説明します。
目次
手順
ステップ 1: Chart.jsのスクリプトを読み込む
functions.php に以下を追加します:
function enqueue_chartjs_scripts() {
wp_enqueue_script('chartjs', 'https://cdn.jsdelivr.net/npm/chart.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_chartjs_scripts');
ステップ 2: カスタムREST APIエンドポイントを作成
PHPでREST APIエンドポイントを作成します。これにより、チャート用のデータを提供できます。
function register_chart_data_endpoint() {
register_rest_route('custom/v1', '/chart-data/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'get_chart_data',
));
}
add_action('rest_api_init', 'register_chart_data_endpoint');
function get_chart_data($data) {
$post_id = $data['id'];
// データ取得 (例: カスタムフィールドからJSONを取得)
$view_history = get_post_meta($post_id, 'view_history', true);
// サンプルデータ (実際にはカスタムフィールドや外部APIから取得)
if (!$view_history) {
$view_history = json_encode([
'2023-01-01' => 12000,
'2023-01-02' => 13000,
'2023-01-03' => 14000,
]);
}
return json_decode($view_history, true);
}
ステップ 3: 記事内でグラフを表示
記事テンプレート(例: single.php)やショートコードで、チャートを表示するHTMLとJavaScriptを追加します。
function render_chart_shortcode($atts) {
$atts = shortcode_atts(array(
'post_id' => get_the_ID(), // 投稿IDを取得
), $atts);
ob_start();
?>
<canvas id="lineChart" width="400" height="200"></canvas>
<script>
document.addEventListener('DOMContentLoaded', function () {
fetch('<?php echo esc_url(rest_url("custom/v1/chart-data/" . $atts["post_id"])); ?>')
.then(response => response.json())
.then(data => {
const labels = Object.keys(data); // 日付
const values = Object.values(data); // 再生数
const ctx = document.getElementById('lineChart').getContext('2d');
const chartData = {
labels: labels,
datasets: [{
label: '動画再生数',
data: values,
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 2,
fill: false,
}]
};
new Chart(ctx, {
type: 'line',
data: chartData,
options: {
responsive: true,
plugins: {
legend: {
display: true,
position: 'top',
},
},
scales: {
x: {
title: {
display: true,
text: '日付'
}
},
y: {
title: {
display: true,
text: '再生数'
},
beginAtZero: true
}
}
}
});
})
.catch(error => console.error('データ取得エラー:', error));
});
</script>
<?php
return ob_get_clean();
}
add_shortcode('render_chart', 'render_chart_shortcode');
実際の利用
記事や固定ページ内で以下のショートコードを利用:
[render_chart post_id="123"]
完成した機能
- 記事内で時系列データを表示する折れ線グラフを実装。
- REST APIでデータを動的に取得。
- Chart.jsを利用してグラフをレンダリング。