I'm looking to set a default value to a specific custom field, in case the client doesn't add into the custom field it already has a specific number associated with it.

one step deeper, I'd like it so if cat =22 is selected this custom field is automatically added into the post with a default that hopefully the client will add the proper number

I think this can be accomplished by a global function but my brain is just not processing this right now

  • Could you please show what you've tried to do (the code)?
    – Lea Cohen
    Jan 29, 2013 at 7:17

2 Answers 2


You can check it by adding a hook to save_post action. In this way all your posts will have default value for a custom field.

add_action( 'save_post', 'wpse8170_save_post', 10, 2 );
function wpse8170_save_post( $post_id, WP_Post $post ) {
    if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || !current_user_can( 'edit_post' ) ) {

    if ( has_category( 22, $post_id ) && !get_post_meta( $post_id, 'my-custom-field', true ) ) {
        update_post_meta( $post_id, 'my-custom-field', 'my default value' );

You would not do this via a global, you simply use the default functionality of add_post_meta.

// your loop
if ( in_category(22)) {

    //check if the meta field has a value
    $meta_values = get_post_meta($post->ID, 'your_meta_key', true);

    //add a default value
    add_post_meta($post->ID, 'your_meta_key', 'some default value');

Reference: http://codex.wordpress.org/Custom_Fields

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.