add custom fields automatically in WordPress og 1 1

Do you need to add custom fields automatically while publishing WordPress posts?

When adding new functionality to a WordPress website, developers can use this simple trick.

Advertisements

In this article, we’ll show you how to automatically add custom fields to WordPress posts after they’re published.

Posts

Why is it necessary to add custom fields automatically?

You can use custom fields to add extra information to your entries. This information can be shown on your website, kept hidden, or used by WordPress themes and plugins to enhance the functioning of your site.

Custom fields can be used in a variety of ways. In our custom fields tips, tricks, and hacks guide, you’ll find a list of useful suggestions.

When you publish a post, you may want a custom field to be created automatically. This is especially true when adding functionality to WordPress so that it may be used for purposes other than blogging.

When we built a gallery website, we employed this strategy. For each item uploaded to the gallery, we wanted to save short URLs. When each post was published, we automatically established a custom field to store the short URL.

For developers trying to take WordPress to the next level, this trick can be really handy.

Adding Custom Fields to Posts Automatically

We’ll add a custom code snippet to your theme’s functions.php file in this tutorial. We don’t advocate this strategy to inexperienced users because even a minor error can result in your website being broken.

Advertisements

If this is your first time adding code to a WordPress file, see tutorial on how to copy and paste code snippets in WordPress. We’ll show you how to use the Code Snippets plugin in this article.

Navigate to the Snippets section of your WordPress dashboard after installing and activating the Code Snippets plugin. You’ll need to click the Add New button once you’re there.

Click the Add New Button to Add a Custom Code Snippet

You must first give the snippet a title, after which you must copy and paste the following code into the code box.

1
2
3
4
5
6
7
8
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
    global $wpdb;
    if(!wp_is_post_revision($post_ID)) {
        add_post_meta($post_ID, 'field-name', 'custom value', true);
    }
}

 

You’ll need to replace ‘field-name’ and ‘custom value’ with the name and value of the custom field you want to utilize.

Paste the Code Snippet in the Code Box

When you’re finished, go to the bottom of the screen and click the Save Changes and Activate button. When you activate the snippet, the custom field will be created every time you publish a post.

Click the Save Changes and Activate Button

We hope this guide showed you how to add custom fields to WordPress posts automatically when they are published.

Advertisements

Leave a Reply