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

ctrmrzij  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(135)
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中添加这段代码时,它会破坏网站。请告诉我这段代码有什么问题?然而,当我粘贴到页面中时,它的代码工作正常。

2jcobegt

2jcobegt1#

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

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

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

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

相关问题