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.
In my last ACF Pro block I did not include the custom fields in the plugin code. This requires work from the user – it should just work, like I did when I used Genesis Custom Blocks.
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.
I’m trying to make a circle using html and css only. But I want a certain percent number like 70% or 80% written inside it. And the cirlce should be only as much complete as the number states.
The codepen where I got the code only uses HTML and CSS:
You can use that.
If you do not want the light grey circle that completes the circle you can change the ‘stroke‘ in .circle-bg from #eee to transparent or #fff.
Very helpful. Thanks.