What is advanced custom fields in wordpress? By default WordPress provides 2 options to add data (title and description). If we need more fields we either have to customize it or use hooks. In this article, we will learn how to make custom fields using ACF (Advanced Custom Fields) plugin.
Alternate options to add custom fields
WordPress has now introduced an option in the page and post editor to add more field. See how to use Custom fields in WordPress post or page template.
How to use Advanced custom fields
The ACF advanced custom fields in wordpress is a very powerful and useful plugin to manage fields in the page editor. Fields are not just available for posts. You can also display custom fields on the page, custom post type, user, taxonomy term, comment, media and custom options pages.
Step 1: Install plugin
In the WordPress plugin manager, search and install ACF (Advanced Custom Fields) plugin. Don’t forget to activate it 🙂
Step 2: Create group rules
Open plugin settings and select “Field Groups”:
Here we will take an example to add custom fields in the page.
Select some more configurations as per your need for example:
Here we will create 2 fields;
The text field:
The image field:
Step 3: Add content in the page
Now, open the page and you will see that the fields that you have created are now appearing in the page.
Add the content
Now save it.
Step 4: Some coding!
Now open the page template file and write the following code.
<?php if( get_field('sub_heading') ): ?> <h2><?php the_field('sub_heading'); ?></h2> <?php endif; ?> <div class="hero"> <?php $image = get_field('hero_image'); ?> <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" /> </div>
This will print the content on the page.
In the above code you will see use of
if condition for field
sub_heading. We wrapped it because it will first check if
sub_heading exists this will print in the page, otherwise it will not print it. This technique will prevent the system to throw PHP error or warnings. The use of
if condition will make sure the data will print only if content is added from the page backend.
The ACF plugin provides many options to configure it. It support many fields and you can customize it as per the requirements. In this article we have created very basic fields. You can see the details from the ACF documentation.
Also see ho to use the next level of Advanced Custom Fields Pro plugin.