X

Add custom field automatically when post or page is publish

Adding this snippet to the functions.php of your wordpress theme will add a custom field to a post or page when published. Don't forget to update the FIELD_NAME and the CUSTOM VALUE.



Code Snippet:


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

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!