Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

How to Add Custom Fields Automatically on Post Publish in WordPress

Automatically creating custom fields when publishing WordPress posts can be a powerful tool in any developer’s toolkit.

We find that this simple trick can help you save time and streamline workflows when adding new features to your WordPress website.

In this article, we’ll show you how to add custom fields automatically on post publish in WordPress.

How to Add Custom Fields Automatically on Post Publish in WordPress

Why Add Custom Fields Automatically?

Custom fields let you add additional information to your posts. This information can be displayed on your website, kept private, or be used by themes and plugins to extend the functionality of your WordPress website.

There are many ways to use custom fields. You’ll find a list of helpful ideas in our custom fields tips, tricks, and hacks guide.

Sometimes you’ll want a custom field to be created automatically whenever you publish a post. This is especially true when you’re adding functionality to WordPress so that you can use it as more than a simple blog.

We used this method when creating a gallery website. We wanted to store short URLs for each item submitted to the gallery. So we automatically created a custom field to store the short URL when each post was published.

This trick can be very useful for developers who are looking to push WordPress to the next level.

Adding Custom Fields Automatically on Post Publish

This method involves adding a custom code snippet to your theme’s functions.php file. We don’t recommend editing your theme files to inexperienced users, because even a small mistake could break your website.

Instead, we’ll show you how to use the WPCode plugin in this tutorial.

WPCode

WPCode makes it easy to add code snippets in WordPress without having to edit your theme’s functions.php file. You can also manage all of your code snippets from one central screen.

If this is your first time adding code to WordPress, then you should check out our guide on how to copy and paste code snippets in WordPress for more details.

To get started, you need to install and activate the free WPCode plugin. If you need help, see our tutorial on how to install a WordPress plugin.

Note: The free version of WPCode has everything you need to add custom code in WordPress. For more advanced features like scheduled snippets, conversion pixels, and more, you can upgrade to WPCode Pro.

Once the plugin is activated, a new menu item labeled ‘Code Snippets’ will be added to your WordPress admin bar. Click on it and then press the ‘Add New’ button on the next screen.

Click the Add New Button to Add Your First Custom Code Snippet in WPCode

From here, navigate to the ‘Add Your Custom Code (New Snippet)’ option and click on the ‘Use snippet’ button underneath it.

Add your new custom code snippet in WPCode

After that, you need to give the snippet a title, and then copy the following code and paste it into the ‘Code Preview’ box.

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 have to replace ‘field-name’ and ‘custom value’ with the actual name and value you want to use for the custom field.

Don’t forget to choose ‘PHP Snippet’ as the code type from the dropdown menu on the right.

Paste code snippet in WPCode code box

Next, scroll down to the ‘Insertion’ section. Here, you’ll need to leave the ‘Auto Insert’ method selected.

Pick the insertion method for your custom code snippet

With the Auto Insert method, the snippet will be automatically inserted and executed in the proper location.

Once you’re done, you’ll need to toggle the switch from ‘Inactive’ to ‘Active’ and then click the ‘Save Snippet’ button.

Save and activate your custom code snippet

Once the snippet is activated, the custom field will be created whenever you publish a post.

We hope this tutorial helped you learn how to add custom fields automatically on post publish in WordPress. You may also want to learn how to display custom fields outside the loop in WordPress or check out our list of must-have WordPress plugins to grow your website.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

18 CommentsLeave a Reply

  1. Jiří Vaněk

    If I have a website with multiple users and want an author bio to be automatically inserted when an article is published, can this guide be used? That is, can custom fields be used to ensure that a short bio of the author is inserted at the beginning depending on who writes the article? I would like it to be automated in this way. Currently, we do this using Elementor, where each author has their template saved and must manually insert it at the beginning.

  2. Sateesh Raghuwanshi

    I need to add this action for custom post type named ‘ad_system’

  3. nayan

    I want to add category Id for the post in the post_meta table. How can be the function function add_custom_field_automatically($post_ID) be twicked to accomodate that?

    Thanks

  4. chris

    Instead of adding the custom field at the time of creating the post, how do I display a custom field by default on the admin page?

    • Editorial Staff

      If you notice, the code above doesn’t have anything related to the custom post types. It only adds to Post and Page “content type”. So you would have to specify the hook for your custom post type.

      Admin

      • puanthanh

        Thanks for the reply. Can you help me out on this code.
        add_action(‘publish_page’, ‘add_custom_field_automatically’);
        add_action(‘publish_post’, ‘add_custom_field_automatically’);
        add_action( ‘save_post’, ‘add_custom_field_automatically’ );

        function add_custom_field_automatically($post_ID) {
        global $post;
        if(!wp_is_post_revision($post_ID)) {
        global $wpdb;
        $user_id = $wpdb->get_var("SELECT post_author FROM $wpdb->posts WHERE ID = $post_ID");
        $themename = $wpdb->get_var("SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = ‘themeperauthor’ AND user_id = $user_id");
        add_post_meta($post_ID, ‘themeperauthor’, $themename, true);
        }
        }
        When the user meta field is changed, I want to automatically delete the custom field value and update with the new one

  5. brian

    I’ve been working on adding some hidden custom fields on post publish/update (by preceding the field name with “_”) but for some reason I have to update the post twice before the wp_postmeta entries are written to the database.

    I’ve tried messing with the priority and experimenting with other action hooks (draft_to_publish, edit_post, etc) but it doesn’t seem to make a difference.

    Any ideas?

  6. Boba

    Thanks for including the source link :)

  7. Piet

    will this work too for custom post types?
    sth like add_action(‘publish_custom-post-typ-name’, ‘add_custom_field_automatically’);

    • Otto

      Yes, it will.

      One downside to this technique that people should be aware of is that if somebody edits a published post, this hook WILL get fired again on the edit. Therefore, you need to check for the meta before adding it, or to update it, or to do whatever makes the most sense for your use-case.

      If you only want to get your code fired off on the initial publish only, then you can use the transition_post_status hook. This hook works like this:


      add_action('transition_post_status','example',10,3);
      function example($new, $old, $post) {
      // $new is the new post status ('publish')
      // $old is the old post status ('draft')
      // $post is the complete Post Object (so use $post->ID for the ID, etc)
      }

      Then, in here you can do a check for something like this:

      if ($new == 'publish' && $old != 'publish')

      To have your code only used when the post status actually transitions to publish from whatever it was before. This hook is fired at the same time as the {$status}_{$post-type} hooks are, so the operation of them is basically the same.

  8. Vivek Parmar

    thanks for this handy tip. previously while using custom fields i have to work manually. now this will do it automatically. thanks for saving precious time of me

Leave A Reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.