Skip to content

How To Automatically Add Custom Fields On Post Publish In WordPress

If you have a created a function or a modification in your theme which requires you to manually add a default custom field whenever you publish a new post, then you’re doing it wrong. Why do it manually when we can automatically add custom fields on posts when they get publish first? It can also helps if you’re creating a site for client.

Just drop the following code into your current theme’s functions.php file:

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

Just field-name and custom value with your Custom Field Name, and the Value. You can use also this trick will custom post types.

Leave a Reply

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