我在PHP和WordPress新手。我试图了解如何在基本的WordPress插件中显示以html和JavaScript生成的图形。
这是我想要显示图形的基本管理页面。
<?php
/*
Plugin Name: Test plugin
Description: A test plugin to demonstrate wordpress functionality
Author: the author
Version: 0.1
*/
add_action('admin_menu', 'test_plugin_setup_menu');
function test_plugin_setup_menu(){
add_menu_page( 'Test Plugin Page', 'Test Plugin', 'manage_options', 'test-plugin', 'test_init' );
}
function test_init(){
echo "<h1>Hello World!</h1>";
}
?>
例如,我将使用chart.js进行绘制,并使用html文件和JavaScript文件。
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="bar-chart" width="800" height="450"></canvas>
JavaScript
// Bar chart
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
datasets: [
{
label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: [2478,5267,734,784,433]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
}
}
});
答案 0 :(得分:0)
这将是最简单的解决方案,排队chart.js之和打印脚本来启动它的菜单HTML输出内:
add_action('admin_menu', 'test_plugin_setup_menu');
function test_plugin_setup_menu(){
add_menu_page( 'Test Plugin Page', 'Test Plugin', 'manage_options', 'test-plugin', 'test_init' );
}
function test_init(){
wp_enqueue_script( 'chart-js', '//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js' );
echo "<h1>Hello World!</h1>";
?>
<canvas id="bar-chart" width="800" height="450"></canvas>
<script>
window.onload = function(){
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
datasets: [
{
label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: [2478,5267,734,784,433]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
}
}
});
};
</script>
<?php
}
但是我建议您以一种标准的方式进行操作,并有条件地将Chart.js和您自己的JavaScript文件加载到菜单页面上,如How do I Enqueue styles/scripts on Certain /wp-admin Pages?
所示