WordPress Snippets at WPcustoms

automatically add custom meta field values to posts

Auto-add custom meta field values with this function to all posts. This can be extended as required and i.e. add the authors nickname as a custom meta field. Options are endless and this gives you a good start to add meta info for all posts without manually setting the values. Make sure to check out the codex for the add_post_meta hook.


/**
 * Snippet Name: automatically add custom meta field values to posts
 * Snippet URL: https://wpcustoms.net/snippets/automatically-add-custom-meta-field-values-posts/
 */
  function wpc_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);
    }
}
add_action('publish_page', 'wpc_add_custom_field_automatically');
add_action('publish_post', 'wpc_add_custom_field_automatically');