Automatically Create a Custom Field


Sponsored Links




WP Canyon did wonderful tricks, this tricks is about how to automatically create a custom field when a post is published. This wonderful method is added some code on your functions.php files on your current theme.

Added Custom Field Automatically On Post - Abigail Clancy

Added Custom Field Automatically On Post - Abigail Clancy


The first time need to do is open your functions.php and paste Automatically Create a Custom Field 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);
	}
}

You’ll need to tweak this code to make it suitable on your cases, example you need to change field-name and the custom value of your custom field. Do you like Automatically Create a Custom Field tricks?

Subscribe to Full RSS Feed

RSS FeedIf you thing this article useful, please consider subscribing to our RSS Feed or e-mail updates and stay updated with us. You can also follow @WPTricksNet on twitter for latest updates.

About WP Tricks

We are WordPress Family, we collected and writed useful tips and tricks for you WordPress. We share it for you...

Related Tips and Trick from Local Data and on The Net


3 Responses to Automatically Create a Custom Field

  1. Good trick. I would like to do this only when the publish action is on a specfic custom post type. Can it be done?

    For example, I have a custom post type called journal. When I hit publish, I want a custom field called ‘custom_post_template’ to be created with the value journalentry.php

    Any thoughts? Thanks!!

  2. Robert Lewis says:

    Can you use this method to add multiple custom fields?

  3. Pingback: How To Automatically added FTP detail on WordPress | Jhez3R

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>