admin管理员组文章数量:1323715
Say I have a custom field in my posts that contains data formatted like so: 10, 20, 70
(the values differ from one post to another).
How can I display a chart on the blog post with this data as, say, a pie chart?
Thanks
Say I have a custom field in my posts that contains data formatted like so: 10, 20, 70
(the values differ from one post to another).
How can I display a chart on the blog post with this data as, say, a pie chart?
Thanks
Share Improve this question asked Sep 11, 2020 at 12:47 PetePete 113 bronze badges1 Answer
Reset to default 1Welcome 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;
}
本文标签: Show chart in post using data passed as custom field
版权声明:本文标题:Show chart in post using data passed as custom field 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742125948a2421941.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论