Using Advanced Custom Fields (ACF) in the Widgets
We know that Advanced Custom Fields (ACF) Plugin is one of the most popular and widely used Plugins for managing custom fields in WordPress. It can be used easily in Posts, Pages, Custom Post Types and even in Taxonomies. But we cannot use its free version directly in the Widgets. In this article, we are going to see how we can use it in the Widgets with the help of another Plugin easily.
You need to download this Addon Plugin Advanced Custom Fields: Widget and activate it. You can check its documentation but its little complicated and we can use it very simply like Posts or Pages.
As usual register a Widget (sidebar) using
register_sidebar()function to hold our new ACF Widget.
Create a new Custom Field Group as we will do for others and select ‘Widget’ on the ‘Location’ section in both the first and last dropdown.
Now we are going to add this Custom Field Group to our Widget. Just drag and drop ‘ACF Widget’ to the sidebar. Select the Custom Field Group we created above in the ‘ACF Group’ dropdown and click on ‘Save’ button. The fields you have created will appear now and you can add the contents you want. Don’t forget to click ‘Save’ once updated. Please note that you cannot able to change the ‘ACF Group’ once saved and you can only able to delete and add again if you want a different one later.
In order to display the ACF data in the Theme, you need to identify the ACF Widget ID. You can use the method given in the Plugin documentation but the easiest way is – getting the ID via Browser Console. Access the Browser’s Console (probably by clicking ‘Inspect Element’ which might differ little depending on Browser you are using) and click on the ACF Widget heading. You will get something like
<div id="widget-25_acf_widget-2" class="widget">and the ending number (‘2’ here) is the Widget ID.
Now we are going to see the important part of this article – how to display the ACF data in our Theme. You can use the same functions like
the_sub_field()etc. And you just need to insert the Widget ID you have identified in the previous step. So this will be the syntax:
get_field('<field name>,'widget_acf_widget_<widget id>')– so you need to insert
'widget_acf_widget_<widget id>'as an extra parameter to the function. Please note that you need to insert the extra Widget ID code in all the functions you are going to use. The same method will apply to ACF Repeaters too and you need to call the WordPress Widget (sidebar)
That’s it and your ACF data from Widget will be displayed on your site in the way you want.