wordpress create custom fields programmatically

How to Create WordPress Custom Field Programmatically

Do you want to create a WordPress custom field programmatically? If yes, we have the perfect guide for you with a few more additional options.

There are many reasons why WordPress is the most popular CMS around the world. But one of the most relevant is to be highly customizable. You can customize many elements of a WordPress website out of which custom fields are also one of them. WordPress has so many further customizable features for them that you can even add the custom fields programmatically on your website.

What are Custom Fields?

A custom field is attached to a post or page, and it stores additional information to be used for a website. It can also be related to any type of post. So, it can gather information related to products, comments, or even custom post types too.

They are stored in the database of your WordPress website under the wp_postmeta table. It contains the parameters meta_id, post_id, meta_key, and meta_value.

database wordpress create custom fields programmatically

Furthermore, you can also store any kind of data in the custom field. They can even be used by frontend and backend users, or by some other PHP script too.

Why Create a Custom Field in WordPress?

Custom fields can be used for achieving a wide range of requirements. Whenever you need to add some piece of additional information related to a post, a custom field can be very useful.

However, custom fields are mostly used by developers to add new features to their websites. One of its most useful applications is using them on the frontend so that the users can fill out a form.

But here are some more examples where a custom field can be used:

  • Attach a “mood” to posts, where you want to reveal how you were feeling when you were writing it.
  • Let the users know if a post is suggested for some specific age range.
  • Store the time needed to read a post.
  • Give a score of a product or post.
  • A reference data that will trigger some script when present.

Apart from this, themes and plugins generally use custom fields to assign special features to specific posts or pages. Similarly, it is also a common practice to use custom fields on user interfaces, both on the frontend and backend.

Now that you are familiar with the importance of custom fields in WordPress, let’s see how can we add them.

How to add Custom Fields in WordPress?

By default, you can add a custom field to any post while editing it in the editor. All you need to do is enable it on the Page options tab, and scroll down to find the custom field meta box.

Simply click on “Add Custom Field” and insert name and value in order to create a custom field manually.

But if you are here, you are surely looking for a way to create the WordPress custom field programmatically. So, let’s go ahead and dive into it.

How to create a WordPress Custom Field Programmatically?

You can easily create a custom field in WordPress programmatically if you have basic technical knowledge in programming.

But before we start, make sure that you backup your website and create a child theme programmatically or use one of the child theme plugins. We will be modifying the delicate files of your website and these changes might also be erased when you update your WordPress theme. However, if you use a child theme, the customizations in these files won’t be affected even after you update your WordPress theme.

If you are not comfortable with changing the theme files directly on your own, you can use plugins like Code Snippets as well. Nonetheless, we will be using the child theme in this tutorial because it’s easier for us.

1. Access functions.php Theme File

After you create a child theme, you can start adding code snippets on your function.php theme file to create the custom fields. Just go to Appearance > Theme Editor and open the functions.php file from your WordPress dashboard. Then, add the code snippets at the bottom of this editor and update the file.

theme editor wordpress create custom fields programmatically

We have used the Divi theme for this tutorial. But the theme editor might appear different on your website depending on the theme you use.

2. Add Code Snippets to Theme Editor

The add_post_meta() function is the one we will be using. It takes three parameters: id of post or page, name of the custom field and its value. A fourth optional parameter can be used to check if the custom field already exists.

So, adding a custom field is as simple as adding the following line to the function.php file of the child theme.

add_post_meta(460, "custom_field_name", "value",true);

This will add a custom field to the post with the id 460.

We have named the custom field simply “custom_field_name” for this demo. But, you can also assign a string as the value (value) and set the optional parameter to true in order to create it only if it doesn’t exist already.

Of course, this is the most simple state of a script to add a custom field to a specific post. It’s not efficient at all because it will work on every page load simultaneously checking if the custom field exists uselessly.

Thankfully, we can improve it much more, to achieve an acceptable solution. The publish_post()  hook will be very useful in this case because it triggers only when a post is published.

add_action('publish_post', 'add_custom_field_automatically');

function add_custom_field_automatically($post_ID) {

if(!wp_is_post_revision($post_ID)) {

add_post_meta($post_ID, 'meta_field', '55',true);
}
}

Because we are using the $post_ID global variable, this will apply to all newly published posts.

Update a Custom Field in WordPress

When you create a custom field in WordPress programmatically, you can also update them if you want with a similar code snippet.

In order to update a custom field, the update_post_meta() function can be used. We’ll also use the same hook as the previous script since it works when you update a post too. Just add the following code snippet to the functions.php file of your website.

add_action('publish_post', 'update_custom_field_automatically');

function update_custom_field_automatically($post_ID) {

if(!wp_is_post_revision($post_ID)) {

update_post_meta($post_ID, 'meta_field', 20);

}

}

This will change the value of the previously created custom field from 55 to 20.

The update_post_meta()  also works as the add_post_meta()  function. It can create a new custom field if it doesn’t exist too.

Remove Custom Fields in WordPress

The use of code snippets is not limited to just creating and updating the custom fields in WordPress. After you create a WordPress custom field programmatically, there might be some situations where you might want to remove them as well.

The function that will allow us to remove all custom fields with a given name (key) is delete_post_meta_by_key(”meta_field”); It only takes the custom field name as its unique parameter.

As we already talked about, the correct way to do this is using a hook. This time, we’ll use the init() hook which is mostly used to initialize plugins and themes. Again, add the following snippets to the functions.php file.

add_action('init', 'remove_custom_field_automatically');

function remove_custom_field_automatically() {

delete_post_meta_by_key( 'meta_field' );

}

To remove custom fields on specific posts, you can use the delete_post_meta() function. It can also be used if a specific value is assigned to the custom field.

This one works in a similar way compared to the previous snippet. But it provides more flexibility to target the removal of specific custom fields.

add_action('publish_post', 'delete_custom_field_automatically');

function delete_custom_field_automatically($post_ID) {

if(!wp_is_post_revision($post_ID)) {

delete_post_meta($post_ID, 'meta_field');

}

}

This script will remove the custom field named “custom_field” of the current post, which is given by the $post_ID variable.

You can also remove a custom field only if a specific value is attached to it. Simply add it as the third parameter.

delete_post_meta($post_ID, 'meta_field',’20’);

That’s it! You can create, update, or delete a custom field in WordPress programmatically now. Just modify these snippets according to your website and you may be able to modify them even more.

Conclusion

This is our tutorial to create a custom field in WordPress programmatically. They can be very useful if you want to provide your users with additional information on your website.

To summarize, we have shown you the code snippets to create custom fields in WordPress. Similarly, we have also provided you with a few more snippets to update and remove the custom fields. They can come in handy in certain circumstances depending on the need of your website.

Custom fields are one of the best features of WordPress and are widely used in WooCommerce too. We even have guides to add custom fields in WooCommerce checkout and reorder WooCommerce checkout fields. If you want to learn more about other customizations in WordPress and WooCommerce, please feel free to go through the following posts:

So can you create the custom fields in WordPress programmatically now? Have you created them before? Do let us know in the comments.