Embed Step-by-Step Chart.js Charts in WordPress

However, as I perceive that not your whole tasks require this particular format, we’ll first discover methods to create a easy dynamic WordPress chart. And most significantly, with out utilizing a single WordPress chart plugin!

This tutorial expects that you’re acquainted with WordPress theme growth and ideally with the Superior Customized Fields (ACF) WordPress plugin.

 

Implementation

For the implementation half, I’ll work with my regular customized Playground theme.

Theme Construction

Let’s focus on the vital information:

  • The single-chart.php file that may register the Single Chart Web page customized template will probably be related to the single-chart.js file. Each will probably be liable for exhibiting a single chart.
  • The tabs.php file that may register the Tabs Web page customized template will probably be related to the multiple-charts.js file. Each will probably be liable for exhibiting Bootstrap tabs that may include charts.
  • Inside the features.php file, I’ll embrace the required Bootstrap and Chart.js information—the identical variations as within the CodePen demo of the earlier tutorial. Inside this perform, there would be the logic for producing the required chart information.
  • Contained in the acf folder, I’ll export in two strategies all the additional fields that I’m going to make use of to be able to reuse them in your themes—you’ll see, in a second, what I am speaking about.
Exporting the ACF fieldsExporting the ACF fieldsExporting the ACF fields

Right here’s the theme construction:

Theme filesTheme filesTheme files

On your comfort, as regular, all of the theme property will probably be accessible on a GitHub repo.

Creating Additional Fields

Should you take a look at the aforementioned tutorial, you’ll discover that every chart information is represented as an object; that is the format that we’ll additionally preserve for our dynamic information.

1
{
2
  bars: {
3
    bar1: ["25", "76", "64", "33", "85", "46", "25"],
4
    bar2: ["32", "68", "77", "29", "88", "65", "60"]
5
  },
6
  labels: [
7
    "Label 1",
8
    "Label 2",
9
    "Label 3",
10
    "Label 4",
11
    "Label 5",
12
    "Label 6",
13
    "Label 7"
14
  ],
15
  legends: { legend1: "Male", legend2: "Feminine" },
16
  title: "Gender Comparability Graph"
17
}

To create the information, we’ll want some fields. Many plugins will help us create additional fields, just like the Advanced Custom Fields (ACF) plugin, the Pods plugin, and many others. For this train, I’ll select the ACF PRO version to make the most of its flexible content field.

Though I’ll make the most of a premium plugin right here for simpler information manipulation, whatever the plugin of your selection, the logic will stay the identical. We’ll create some fields, then use the plugin features to seize them, and at last format the information earlier than sending them in JavaScript.

Once more, as talked about above, all of the ACF fields will probably be exported each as JSON and PHP and reside contained in the acf theme folder.

As a spoiler, to show to you that regardless of WordPress plugins, different instruments allow us to equally create further web page fields, I am going to present you methods to create a Theme Settings web page utilizing Carbon Fields in an upcoming tutorial.

Create a Single Chart

We’ll begin exhibiting methods to embed a vertical bar chart in a WordPress web page.

The single chart layoutThe single chart layoutThe single chart layout

Utilizing ACF, we’ll create a brand new discipline group and map it to the web page we wish—in my case, this would be the web page with the Single Chart Web page template.

The group field for a single chartThe group field for a single chartThe group field for a single chart

Inside that group, we’ll outline three sub-fields.

The fields for each chartThe fields for each chartThe fields for each chart

Contained in the Legends subfield, we’ll specify two further fields for labeling the datasets that may seem on the backside of the chart.

The legend's sub fieldsThe legend's sub fieldsThe legend's sub fields

The Rows versatile content material discipline will enable us to create an infinite variety of rows the place every row will symbolize a single set of vertical bars—think about it as a repeater with rows that may be collapsed.

A single set of vertical barsA single set of vertical barsA single set of vertical bars
The rows' sub fieldsThe rows' sub fieldsThe rows' sub fields

After setting the fields, we’ll navigate to the admin of the goal web page and fill them with information.

The single chart dataThe single chart dataThe single chart data

Within the single-chart.php file,  we have already got a reference to the required canvas component that Chart.js expects:

1
<?php
2
/*
3
Template Title: Single Chart Web page
4
*/
5
get_header();
6
?>
7

8
<essential class="site-main">
9
    <?php
10
    if ( have_posts() ) :
11
        whereas ( have_posts() ) :
12
            the_post();
13
            ?>
14
            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
15
                <div class="container my-5">
16
                    <canvas id="myChart"></canvas>
17
                </div>
18
            </article>
19
            <?php
20
        endwhile;
21
    endif;
22
    ?>
23
</essential>
24

25
<?php
26
get_footer();

From there, we’ll swap to the features.php file and create a perform, which is able to run just for pages whose template is the Single Chart Web page one, for producing the chart information within the desired format:

1
perform get_single_chart() {
2
    $chart_single  = (object) array(
3
        'legends' => (object) array(),
4
        'labels'  => array(),
5
        'bars'    => (object) array(
6
            'bar1' => array(),
7
            'bar2' => array(),
8
        ),
9
        'title'   => '',
10
    );
11
    $chart         = get_field( 'chart' );
12
    $chart_legends = $chart['legends'];
13

14
    $chart_single->title            = esc_html( $chart['title'] );
15
    $chart_single->legends->legend1 = esc_html( $chart_legends['legend1'] );
16
    $chart_single->legends->legend2 = esc_html( $chart_legends['legend2'] );
17
    
18
    foreach ( $chart['rows'] as $row ) :
19
        array_push( $chart_single->labels, esc_html( $row['label'] ) );
20
        array_push( $chart_single->bars->bar1, esc_html( $row['bar1'] ) );
21
        array_push( $chart_single->bars->bar2, esc_html( $row['bar2'] ) );
22
    endforeach;
23
    
24
    return $chart_single;
25
}

For simplicity, we’ll skip further checks like making certain that the rows array is not empty, and many others.

Right here’s an instance of the generated information:

The chart data that are sent to the JavaScriptThe chart data that are sent to the JavaScriptThe chart data that are sent to the JavaScript

We’ll go these information by means of the wp_localize_script() perform with the assistance of the global_obj object to the related JavaScript file.

1
perform playground_scripts_and_styles() {    
2
    ...
3
    if ( is_page_template( 'page-templates/single-chart.php' ) ) :
4
        wp_enqueue_script( 'playground-script-single-chart', $theme_uri . '/property/js/single-chart.js', array(), null, true );
5
        wp_localize_script(
6
            'playground-script-single-chart',
7
            'global_obj',
8
            array(
9
                'chart' => get_single_chart(),
10
            )
11
        );
12
    endif;
13
}
14
add_action( 'wp_enqueue_scripts', 'playground_scripts_and_styles' );

Subsequent, within the single-chart.js file, we’ll seize the PHP information utilizing the global_obj.chart property and print the vertical bar chart with the next code:

1
Chart.defaults.font.household = "Poppins, sans-serif";
2
Chart.defaults.coloration = "#073b4c";
3

4
const chart = global_obj.chart;
5

6
const information = {
7
  labels: chart.labels,
8
  datasets: [
9
    {
10
      label: chart.legends.legend1,
11
      data: chart.bars.bar1,
12
      backgroundColor: "#dc3545",
13
    },
14
    {
15
      label: chart.legends.legend2,
16
      data: chart.bars.bar2,
17
      backgroundColor: "#198754",
18
    },
19
  ],
20
};
21

22
const config = {
23
  sort: "bar",
24
  information,
25
  choices: {
26
    plugins: {
27
      title: {
28
        show: true,
29
        textual content: chart.title,
30
        place: "high",
31
        font: {
32
          measurement: 25,
33
        },
34
        padding: {
35
          high: 15,
36
          backside: 15,
37
        },
38
      },
39
      legend: {
40
        place: "backside",
41
        labels: {
42
          padding: 30,
43
          font: {
44
            measurement: 14,
45
          },
46
        },
47
      },
48
      tooltip: {
49
        enabled: false,
50
      },
51
    },
52
    scales: {
53
      y: {
54
        ticks: {
55
          crossAlign: "left",
56
          callback: perform (val) {
57
            return `${val}%`;
58
          },
59
        },
60
      },
61
    },
62
  },
63
};
64

65
const ctx = doc.getElementById("myChart").getContext("2nd");
66
new Chart(ctx, config);

Combine Bootstrap Tabs With Charts

Let’s now go a step additional and recreate the format of the earlier tutorial.

The tabs layoutThe tabs layoutThe tabs layout

Utilizing ACF, we’ll create a brand new versatile content material discipline and map it to the web page we wish—in my case, this would be the web page with the Tabs Web page template.

The tabs flexible content fieldThe tabs flexible content fieldThe tabs flexible content field

For every tab, we’ll outline two fields: its identify and the information for the embedded chart.

The fields of each tabThe fields of each tabThe fields of each tab

The sub-fields of the Chart group discipline are the identical because the fields of the Chart group discipline of the Single Chart Web page template.

After setting the fields, we’ll navigate to the admin of the goal web page and create as many tabs as we wish.

Creating tabs through the adminCreating tabs through the adminCreating tabs through the admin

Every tab will seem like this:

The fields inside each tabThe fields inside each tabThe fields inside each tab

Within the tabs.php file,  we’ll loop by means of the tabs, and for every one, we’ll create the suitable canvas component that Chart.js expects:

1
<?php
2
/*
3
Template Title: Tabs Web page
4
*/
5
get_header();
6
?>
7

8
<essential class="site-main">
9
    <?php
10
    if ( have_posts() ) :
11
        whereas ( have_posts() ) :
12
            the_post();
13
            $tabs = get_field( 'tabs' );
14
            ?>
15
            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
16
                <div class="container my-5">
17
                    <ul class="nav nav-tabs" id="myTab" function="tablist">
18
                        <?php
19
                        foreach ( $tabs as $key => $tab ) :
20
                            $active_class  = 0 === $key ? ' lively' : '';
21
                            $aria_selected = 0 === $key ? true : false;
22
                            $quantity        = ++$key;
23
                            ?>
24
                            <li class="nav-item" function="presentation">
25
                                <button class="nav-link<?php echo $active_class; ?>" id="chart<?php echo $quantity; ?>-tab" data-bs-toggle="tab" data-bs-target="#chart<?php echo $quantity; ?>-tab-pane" sort="button" function="tab" aria-controls="chart<?php echo $quantity; ?>-tab-pane" aria-selected="<?php echo $aria_selected; ?>">
26
                                    <?php echo esc_html( $tab['title'] ); ?>
27
                                </button>
28
                            </li>
29
                        <?php endforeach; ?>
30
                    </ul>
31
                    <div class="tab-content mt-5" id="myTabContent">
32
                        <?php
33
                        foreach ( $tabs as $key => $tab ) :
34
                            $active_class = 0 === $key ? ' present lively' : '';
35
                            $quantity       = ++$key;
36
                            ?>
37
                            <div class="tab-pane fade<?php echo $active_class; ?>" id="chart<?php echo $quantity; ?>-tab-pane" function="tabpanel" aria-labelledby="chart<?php echo $quantity; ?>-tab" tabindex="0">
38
                                <canvas id="myChart<?php echo $quantity; ?>"></canvas>
39
                            </div>
40
                        <?php endforeach; ?>
41
                    </div>
42
                </div>
43
            </article>
44
            <?php
45
        endwhile;
46
    endif;
47
    ?>
48
</essential>
49

50
<?php
51
get_footer();

From there, we’ll swap to the features.php file and create a perform, which is able to run just for pages whose template is the Tabs Web page one, for producing the chart information within the desired format:

1
perform get_multiple_charts() {
2
    $charts = array();
3
    $tabs   = get_field( 'tabs' );
4
    foreach ( $tabs as $tab ) :
5
        $chart_single  = (object) array(
6
            'legends' => (object) array(),
7
            'labels'  => array(),
8
            'bars'    => (object) array(
9
                'bar1' => array(),
10
                'bar2' => array(),
11
            ),
12
            'title'   => '',
13
        );
14
        $chart         = $tab['chart'];
15
        $chart_legends = $chart['legends'];
16
        
17
        $chart_single->title            = esc_html( $chart['title'] );
18
        $chart_single->legends->legend1 = esc_html( $chart_legends['legend1'] );
19
        $chart_single->legends->legend2 = esc_html( $chart_legends['legend2'] );
20
        
21
        foreach ( $chart['rows'] as $row ) :
22
            array_push( $chart_single->labels, esc_html( $row['label'] ) );
23
            array_push( $chart_single->bars->bar1, esc_html( $row['bar1'] ) );
24
            array_push( $chart_single->bars->bar2, esc_html( $row['bar2'] ) );
25
        endforeach;
26
        array_push( $charts, $chart_single );
27
    endforeach;
28
    
29
    return $charts;
30
}

Once more, for simplicity, we’ll skip further checks like making certain that the rows array is not empty, and many others.

Right here’s an instance of the generated information:

The chart data that are sent to the JavaScriptThe chart data that are sent to the JavaScriptThe chart data that are sent to the JavaScript

We’ll go these information by means of the wp_localize_script() perform with the assistance of the global_obj object to the related JavaScript file.

1
perform playground_scripts_and_styles() {
2
    ...
3
    if ( is_page_template( 'page-templates/tabs.php' ) ) :
4
        wp_enqueue_script( 'playground-script-multiple-charts', $theme_uri . '/property/js/multiple-charts.js', array(), null, true );
5
        wp_localize_script(
6
            'playground-script-multiple-charts',
7
            'global_obj',
8
            array(
9
                'charts' => get_multiple_charts(),
10
            )
11
        );
12
    endif;
13
}
14
add_action( 'wp_enqueue_scripts', 'playground_scripts_and_styles' );

Subsequent, within the multiple-charts.js file, we’ll seize the PHP information utilizing the global_obj.charts property and print the vertical bar charts with the identical code we used within the earlier tutorial.

1
const tabEls = doc.querySelectorAll('button[data-bs-toggle="tab"]');
2

3
Chart.defaults.font.household = "Poppins, sans-serif";
4
Chart.defaults.coloration = "#073b4c";
5

6
initializeSingleChart(0);
7

8
tabEls.forEach(perform (tabEl) {
9
  tabEl.addEventListener("proven.bs.tab", perform (occasion) {
10
    const index = Array.from(tabEls).indexOf(occasion.goal);
11
    initializeSingleChart(index);
12
  });
13
});
14

15
perform initializeSingleChart(index) {
16
  const chart = global_obj.charts[index];
17
  const chartEl = `myChart${++index}`;
18
  const chartInstance = Chart.getChart(chartEl);
19
  
20
  if (chartInstance !== undefined) {
21
    chartInstance.destroy();
22
  }
23

24
  const information = {
25
    labels: chart.labels,
26
    datasets: [
27
      {
28
        label: chart.legends.legend1,
29
        data: chart.bars.bar1,
30
        backgroundColor: "#dc3545"
31
      },
32
      {
33
        label: chart.legends.legend2,
34
        data: chart.bars.bar2,
35
        backgroundColor: "#198754"
36
      }
37
    ]
38
  };
39

40
  const config = {
41
    sort: "bar",
42
    information,
43
    choices: {
44
      plugins: {
45
        title: {
46
          show: true,
47
          textual content: chart.title,
48
          place: "high",
49
          font: {
50
            measurement: 25
51
          },
52
          padding: {
53
            high: 15,
54
            backside: 15
55
          }
56
        },
57
        legend: {
58
          place: "backside",
59
          labels: {
60
            padding: 30,
61
            font: {
62
              measurement: 14
63
            }
64
          }
65
        },
66
        tooltip: {
67
          enabled: false
68
        }
69
      },
70
      scales: {
71
        y: {
72
          ticks: {
73
            crossAlign: "left",
74
            callback: perform (val) {
75
              return `${val}%`;
76
            }
77
          }
78
        }
79
      }
80
    }
81
  };
82

83
  const ctx = doc.getElementById(chartEl).getContext("2nd");
84
  new Chart(ctx, config);
85
}

Conclusion

Performed! That was a extremely massive tutorial of us, however I hope that you just’ve discovered so much and now have a very good understanding of methods to embed Chart.js charts in WordPress in customized layouts with out having to embed a WordPress chart plugin.

In fact, right here we labored with the Bootstrap framework and the ACF plugin, however the methodology stays the identical whatever the front-end/CSS framework or fields plugin you’re going to make use of.

As all the time, thanks so much for studying!

Trending Merchandise
[product_category category=”trending” per_page=”8″ columns=”2″ orderby=”date” order=”desc”].

We will be happy to hear your thoughts

Leave a reply

MyStudioCafe
Logo
Compare items
  • Total (0)
Compare
0