Block to display a percentage circle with animation. Based on: https://codepen.io/sergiopedercini/pen/jmKdbj
I recently had a need for a Percentage Circle with animation. I found a nice one on codepen – SVG percentage circle with css keyframes animation – complete example.
I incorporated the code into a shortcode, with parameters for the percentage, colour and text. It was simple and it worked.
I am a big fan of the WordPress block editor and I previously experimented with using Advanced Custom Fields Pro to create a Flip Card block. I also experimented with Genesis Custom Blocks.
For the Percentage Circle block I choose to use ACF Pro as it renders the block in the editor. For those that don’t have ACF Pro it would not be difficult to convert the code to work with Genesis Custom Blocks. I have written about the front end impact of ACF so, if you are not using ACF then Genesis Custom Blocks would be a better choice.
Automatically add custom fields
Blocks developed with ACF Pro have two basic components – custom fields and a registered block.
I created the custom fields in the Dashboard and the exported the PHP (via Custom Fields/Tools/Export Field Groups/Generate PHP. To make the code a little shorter I removed some of the settings that I knew had the default values.
I added the PHP code to the acf/init function, after the acf_register_block_type() call as the ‘location‘ setting for the field group references the block name.
Block template & CSS
Looking at Sergio’s pen I saw where the percentage and text are set. The colour is set via CSS so I did a little experimenting and I was able to incorporate it into the SVG markup.
The CSS is the minimal amount to make it work – .circular-chart, .circle-bg, .circle and progress animation. I changed the animation length from 1 second to 2 seconds.
Using the code
To use this code you will need to have Advanced Custom Fields Pro installed and active. Download all 3 files and upload them to a new directory under wp-content/plugins. Then activate the plugin and you’re ready to go.