X

How To Add a Custom Field to a Post or Page When It Is Published

Snippets by IsItWP

Are you looking for a way to add a custom field to a post or page when it is published? This snippet will add a custom field, with a name and value of your choice, to a post or page when it is published.

Instructions:

  1. Add this code to your theme’s functions.php file or in a site-specific plugin.
  2. Replace the FIELD_NAME text and the CUSTOM VALUE text to the name and value of your choice.
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);
    }
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 7 Best Drag and Drop WordPress Page Builders Compared.

Comments   Leave a Reply

  1. Nice! And I guess we can use published_to_post hook to change that value. Or even better:


    function post_unpublished( $new_status, $old_status, $post ) {
    if ( $old_status == 'publish' && $new_status != 'publish' ) {
    // Post is unpublished
    }
    }
    add_action( 'transition_post_status', 'post_unpublished', 10, 3 );

    Any better way to do it?

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!