Show chart in post using data passed as custom field

Welcome to WPSE.

The first thing to note is that you may want to put any custom code you write for this functionality into a custom plugin. This way the functionality is theme independent and available to you even, if you someday change the theme you’re using.

The modern way would be to create a custom block, which handles the saving and rendering of the chart data. This might require serious amount of involvement depending how fancy you want to make the custom block.

A little easier option is to create a custom shortcode that reads the post meta data and returns the html markup for the chart. The good thing about a custom block or a shortcode is that you can put it anywhere on the post content – top, middle, bottom – or use it multiple times.

A simplified solution would be to either append or prepend the chart html to the post content by using the_content filter. This has the downside that the chart will either be at the top or bottom of the content.

And you’ll probably want to use some kind of javascript chart library to handle the actual rendering of the chart. Use your favourite search engine to find one (e.g. google js charts and see what comes up). You’ll need to enqueue library related js and css files.

To access the post meta in the shortcode or filter callbacks, you can use get_post_meta() function.

Here’s a simplified shortcode example,

// add to custom plugin file or (child) theme functions.php file
add_shortcode( 'footag', 'wpdocs_footag_func' );
function wpdocs_footag_func( $atts ) {
    // read post meta of the current post
    // you could also pass the post id as a shortcode attribute ($atts)
    $meta = get_post_meta( get_the_ID(), 'your_chart_data_meta_key', true );
    // helper variable to contain html output
    $output="";
    // do stuff, if chart data exists
    if ( $meta ) {
        $output="<div class="chart">some html markup here</div>";
    }
    // Shortcode should return not echo its output
    return $output; 
}

Leave a Comment