Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I´m trying to find a snippet to add a predefined custom field. Does anyone know how or where i can find this?

I know I can do this with CustomPress, but I´m trying to do this without a plugin.

share|improve this question
take a look at github.com/bainternet/My-Meta-Box – Bainternet Sep 12 '12 at 12:32

1 Answer

Take a look at adding a custom meta box for any type of predefined meta field.

add_meta_box - Docs - WordPress

You will need to add a hook to the 'save_post' action in order to save the meta data also.

Here is a quick and simple version:

    add_action( 'save_post', 'your_meta_box_save' );

    add_action( 'add_meta_boxes', 'your_meta_box_add' );

function your_meta_box_add(){
        add_meta_box( 'predefined_field', 'Your Predefined Info', 'your_meta_box_html', 'post', 'normal', 'high' );
}

function your_meta_box_save( $post_id ){

    // Bail if we're doing an auto save
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    // if our nonce isn't there, or we can't verify it, bail
    if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'your_meta_box_nonce' ) ) return;

    // if our current user can't edit this post, bail
    if( !current_user_can( 'edit_post' ) ) return;

    // now we can actually save the data
    $allowed = array( 
        'a' => array( // on allow a tags
            'href' => array() // and those anchords can only have href attribute
        )
    );

    $your_predefined_value = isset($_POST['your_predefined_field']) ? $_POST['your_predefined_field'] : '';

    if( $your_predefined_value )
        update_post_meta($post_id,'your_predefined_field',$your_predefined_value);

}

function your_meta_box_html( $post ){

    wp_nonce_field( 'your_meta_box_nonce', 'meta_box_nonce' );

    //if you know it is not an array, use true as the third parameter
    $your_predefined_value = get_custom_meta($post->ID,'your_predefined_field',true);

    ?>

            <input name="your_predefined_field" id="your_predefined_field" type="text"  value="<?php echo $your_predefined_value; ?>" class="mws-textinput" />
    <?php
}

That should get you started; comment back if something is amiss.

share|improve this answer

Your Answer

 
discard

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.