WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
Could you please show what you've tried to do (the code)? – Lea Cohen Jan 29 '13 at 7:17

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' );
share|improve this answer

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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