当我在functions.php中添加这段代码时,它会破坏网站,我的短代码中的Wong是什么?Chart.js

ctrmrzij  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(181)
  1. function chartJS_shortcode(){
  2. ?><canvas id="myChart" width="400" height="400"></canvas><?php
  3. <script>
  4. const ctx = document.getElementById('myChart').getContext('2d');
  5. const myChart = new Chart(ctx, {
  6. type: 'bar',
  7. data: {
  8. labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
  9. datasets: [{
  10. label: '# of Votes',
  11. data: [12, 19, 3, 5, 2, 3],
  12. backgroundColor: [
  13. 'rgba(255, 99, 132, 0.2)',
  14. 'rgba(54, 162, 235, 0.2)',
  15. 'rgba(255, 206, 86, 0.2)',
  16. 'rgba(75, 192, 192, 0.2)',
  17. 'rgba(153, 102, 255, 0.2)',
  18. 'rgba(255, 159, 64, 0.2)'
  19. ],
  20. borderColor: [
  21. 'rgba(255, 99, 132, 1)',
  22. 'rgba(54, 162, 235, 1)',
  23. 'rgba(255, 206, 86, 1)',
  24. 'rgba(75, 192, 192, 1)',
  25. 'rgba(153, 102, 255, 1)',
  26. 'rgba(255, 159, 64, 1)'
  27. ],
  28. borderWidth: 1
  29. }]
  30. },
  31. options: {
  32. scales: {
  33. y: {
  34. beginAtZero: true
  35. }
  36. }
  37. }
  38. });
  39. </script>
  40. }
  41. add_shortcode("chartJS", "chartJS_shortcode");

我想通过chart.js创建一个图表简码,当我在functions.php中添加这段代码时,它会破坏网站。请告诉我这段代码有什么问题?然而,当我粘贴到页面中时,它的代码工作正常。

2jcobegt

2jcobegt1#

将JavaScript放在它自己的文件中。这样做的原因是,您只想加载脚本一次,这样可以使您的短代码更简洁。让我们将该文件命名为chart.js
让我们用wp_register_script注册该脚本以进行排队,这意味着只要我们给予信号,它就会被添加到页面中。

  1. add_action('wp_enqueue_scripts', function() {
  2. wp_register_script('chartJS', 'your-assets-folder/chart.js', [], false, true);
  3. });

然后是简短代码。因为脚本现在在一个单独的文件中,代码更简洁了。这里我们调用wp_enqueue_script将JS添加到页面底部。
这里最重要的部分是以字符串的形式返回HTML,这将是短代码的输出。

  1. add_shortcode('chartJS', function($atts, $content = null) {
  2. wp_enqueue_script('chartJS');
  3. return '<canvas id="myChart" width="400" height="400"></canvas>';
  4. });

相关问题