function chartJS_shortcode(){
?><canvas id="myChart" width="400" height="400"></canvas><?php
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
}
add_shortcode("chartJS", "chartJS_shortcode");
我想通过chart.js创建一个图表简码,当我在functions.php中添加这段代码时,它会破坏网站。请告诉我这段代码有什么问题?然而,当我粘贴到页面中时,它的代码工作正常。
1条答案
按热度按时间2jcobegt1#
将JavaScript放在它自己的文件中。这样做的原因是,您只想加载脚本一次,这样可以使您的短代码更简洁。让我们将该文件命名为
chart.js
让我们用
wp_register_script
注册该脚本以进行排队,这意味着只要我们给予信号,它就会被添加到页面中。然后是简短代码。因为脚本现在在一个单独的文件中,代码更简洁了。这里我们调用
wp_enqueue_script
将JS添加到页面底部。这里最重要的部分是以字符串的形式返回HTML,这将是短代码的输出。