WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Tutorials» How to Add Custom Fields Automatically on Post Publish in WordPress

How to Add Custom Fields Automatically on Post Publish in WordPress

Last updated on June 22nd, 2012 by Editorial Staff
13 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
How to Add Custom Fields Automatically on Post Publish in WordPress

When creating our WPBeginner Gallery Site, we needed to generate custom branded short urls automatically for each site submitted to the gallery, and then store them as a custom field as soon as the post was published. Now while we will leave the auto-generating Bit.ly shortlinks for each post for our next topic, we will cover how to add custom fields automatically on post publish in WordPress. This can be very useful for developers who are looking to push WordPress to the next level.

First thing you need to do is open your theme’s functions.php file and paste the following code:

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);
	}
}

Then simply replace the field-name and custom value with your Custom Field Name, and the Value. This is a relatively simple trick, but it can be very effective when trying to use WordPress for other than blog purposes.

Source: WPCanyon

13 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • How to Properly Move Your Blog from WordPress.com to WordPress.org

  • Checklist

    Checklist: 15 Things You MUST DO Before Changing WordPress Themes

  • Revealed: Why Building an Email List is so Important Today (6 Reasons)

    Revealed: Why Building an Email List is so Important Today (6 Reasons)

  • Google Analytics in WordPress

    How to Install Google Analytics in WordPress for Beginners

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

18 Comments

Leave a Reply
  1. 李国安 says:
    Jul 10, 2014 at 9:19 am

    This action hooks has been deprecated since Version 2.3.

    Reply
  2. Sateesh Raghuwanshi says:
    Aug 8, 2013 at 9:29 am

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

    Reply
  3. Ilan Perez says:
    Oct 25, 2012 at 8:53 pm

    I have tried your code block above and nothing happens.

    The new fields aren’t added to to post.

    Reply
  4. nayan says:
    Oct 30, 2011 at 12:52 am

    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

    Reply
  5. chris says:
    Mar 15, 2011 at 8:30 pm

    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?

    Reply
  6. puanthanh says:
    Mar 1, 2011 at 3:59 pm

    it’s not adding to custom post type

    Reply
    • Editorial Staff says:
      Mar 1, 2011 at 7:03 pm

      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.

      Reply
      • puanthanh says:
        Mar 1, 2011 at 8:00 pm

        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

        Reply
  7. brian says:
    Feb 14, 2011 at 7:06 pm

    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?

    Reply
    • Editorial Staff says:
      Feb 15, 2011 at 2:36 pm

      are you using Otto’s trick with the transient API?

      Reply
  8. Boba says:
    Feb 2, 2011 at 5:26 am

    Thanks for including the source link :)

    Reply
    • Editorial Staff says:
      Feb 2, 2011 at 6:37 am

      Thanks for providing an amazing tip :)

      Reply
  9. Daniel Suarez says:
    Feb 1, 2011 at 10:30 am

    Thanks Otto another great tip!

    Reply
  10. Piet says:
    Jan 31, 2011 at 11:06 pm

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

    Reply
    • Otto says:
      Feb 1, 2011 at 4:39 am

      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.

      Reply
      • Piet says:
        Feb 1, 2011 at 4:43 am

        Thanks Otto, will play around with that a bit!

        Reply
      • Editorial Staff says:
        Feb 1, 2011 at 10:56 am

        Thanks Otto for the clarification.

        Reply
  11. Vivek Parmar says:
    Jan 31, 2011 at 12:05 pm

    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

    Reply

Leave a Reply Cancel 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.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
All in One SEO
Improve website SEO rankings with AIOSEO plugin. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2021 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2021)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2021)
    • SiteGround Reviews from 4464 Users & Our Experts (2021)
    • Bluehost Review from Real Users + Performance Stats (2021)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2021 – Step by Step Guide
Deals & Coupons (view all)
LiveChat logo
LiveChat Inc Coupon
Get a 30 day free trial and 30% OFF LiveChat, one of the best live chat service providers for WordPress users.
LearnDash
LearnDash Coupon
Get the lowest price on the best learning management system (LMS) plugin for WordPress.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).

Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
  • Growth Fund
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon
  • AIOSEO

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress Security by Sucuri.