What are 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 fields. 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 the 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 “Custom Fields” and select “Field Groups”:
Here we will take an example to add custom fields to 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 to the page
Now, open the page and you will see that the fields that you have created are now appearing on the page.
Add the content and 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 the use of if conditions for the field sub_heading. We wrapped it because it will first check if sub_heading exists this will print on the page, otherwise it will not print it. This technique will prevent the system to throw PHP errors or warnings. The use of if the condition will make sure the data will print only if the content is added from the page backend.
The ACF plugin provides many options to configure it. It supports 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 how to use the next level of the Advanced Custom Fields Pro plugin.