Automatically Add Specific Custom Field Content in WordPress
In WordPress development, you may need to automatically add predefined custom fields (post meta) to specific post types. This can be achieved using the save_post hook. The following example code automatically adds a custom field named market_value with the value TEST_STRING when a post of type inventory is saved.
add_action( 'save_post', 'update_tmv' );
function update_tmv($postid) {
if ( !wp_is_post_revision( $postid ) && get_post_type( $postid ) == 'inventory') {
$field_name = 'market_value';
add_post_meta($postid, $field_name, 'TEST_STRING', true);
}
}
Code Explanation
add_action( 'save_post', 'update_tmv' );: Hooks the custom functionupdate_tmvto thesave_postaction, which triggers when a post (or custom post type) is saved.!wp_is_post_revision( $postid ): This condition ensures the code does not run when saving a post revision, preventing duplicate additions.get_post_type( $postid ) == 'inventory': This condition restricts the operation to posts of typeinventory. Modify this type according to your needs.add_post_meta($postid, $field_name, 'TEST_STRING', true);: This is the core function for adding the custom field. The last parametertruemeans if the field already exists, its value is preserved (not updated). To force an update toTEST_STRINGon every save, use theupdate_post_metafunction instead.
Important Notes
- Add this code to your current theme's
functions.phpfile or a custom functionality plugin. - Modify
inventory(post type),market_value(field name), andTEST_STRING(field value) based on your actual requirements. - If you want the field value to be updatable on subsequent saves, consider replacing
add_post_metawithupdate_post_meta. - In a production environment, use meaningful dynamic data for the field value rather than a fixed test string.