How to Add Custom Fields Automatically on Post Publish in WordPress

86

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