W
WP Quick Search
Features Integration Pricing Documentation Blog Products Demo
Login Start for free
Login Start for free
Blog / WordPress/ How to Automatically Add Custom Field Content in WordPress

How to Automatically Add Custom Field Content in WordPress

2018-03-10 · Ryan · Post Comment
wordpress自动添加指定自定义字段的内容

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 function update_tmv to the save_post action, 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 type inventory. 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 parameter true means if the field already exists, its value is preserved (not updated). To force an update to TEST_STRING on every save, use the update_post_meta function instead.

Important Notes

  1. Add this code to your current theme's functions.php file or a custom functionality plugin.
  2. Modify inventory (post type), market_value (field name), and TEST_STRING (field value) based on your actual requirements.
  3. If you want the field value to be updatable on subsequent saves, consider replacing add_post_meta with update_post_meta.
  4. In a production environment, use meaningful dynamic data for the field value rather than a fixed test string.
Custom FieldsDevelopmentHooksPHPPost Metasave_postWordPress
Previous
How to Dynamically Update Permalink and Title Using Custom Field Values in WordPress
Next
Essential WordPress Hooks for Content Publishing

Post a Comment Cancel reply

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

Quick Navigation
W
WP Quick Search
About Terms of Service Privacy Policy
© 2026 WP Quick Search Inc. All rights reserved. ·
14 0.032s 4.23MB

Notice