1

I've tried almost anything and just can't get this to work.

I have a custom post type with a custom meta field and I want a default value to be added on when the Publish/Update/Save button is pressed.

I tried all kind of hooks wp_insert_post, save_post, edit_post..

add_action('save_post_post_type', 'set_default_meta', 10, 3);

And my function is:

function set_default_meta( $post_ID ) {

    $meta_value = get_post_meta($post_ID, 'meta_value', true);

    if ( $meta_value == '' && !wp_is_post_revision($post_ID) ) {
        add_post_meta( $post_ID, 'meta_value', 0, true );
    }
}

When I publish the post, the value is not saved. However whenI click View Post, the value is immediately saved.

Any help will be really appreciated!

1 Answer 1

2

Use update_post_meta(), because if the meta key already exists add_post_meta() will do nothing if $unique is true and otherwise won't update neither, while update_post_meta(), well, it will update the value of a existing field or create it, if it doesn't exist yet.

2
  • Oh gosh, thank you! I lost all day looking at hooks and stuff and lost all day.... you saved me another one. Hmm, saw somewhere that priory should be at least one, but it's working without one.
    – Ziik
    Commented Mar 24, 2015 at 15:06
  • My pleasure! Haven't we all overlooked something sometime.. Default priority is 10, so not a problem, unless you want a specific one. @Ziik Commented Mar 24, 2015 at 15:10

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.