How to add a custom field or meta box in wordpress post or any custom post type in admin side

For add a meta box or custom filed to your any post type  just copy below code and add it into your theme's functions.php file and change according to you need.


function rj_feature_video_add_meta_box() {
    $screens = array( 'firework-video' );   // change post type slugs
    foreach ( $screens as $screen ) {
        add_meta_box(
            'feature_video_fireworks',
            __( 'Feature Video', 'flatsome' ),
            'rj_feature_video_fireworks_meta_box_callback',
            $screen
        );
    }
}
add_action( 'add_meta_boxes', 'rj_feature_video_add_meta_box' );

function rj_feature_video_fireworks_meta_box_callback( $post ) {

    wp_nonce_field( 'rj_feature_video_meta_box', 'rj_feature_video_nonce' );

    $value = get_post_meta( $post->ID, '_rj_feature_firwork_video', true );
    echo '<label for="feature_video_fireworks_field">';
    _e( 'Feature Video Link', 'flatsome' );
    echo '</label> ';
    echo '<textarea type="text" id="feature_video_fireworks_field" name="feature_video_fireworks_field" size="25" />' . esc_attr( $value ) . '</textarea>';
}
function rj_save_firework_feature_video( $post_id ) {
    if ( ! isset( $_POST['rj_feature_video_nonce'] ) ) {
        return;
    }
    if ( ! wp_verify_nonce( $_POST['rj_feature_video_nonce'], 'rj_feature_video_meta_box' ) ) {
        return;
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
        if ( ! current_user_can( 'edit_page', $post_id ) ) {
            return;
        }
    } else {
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
    }
    if ( ! isset( $_POST['feature_video_fireworks_field'] ) ) {
        return;
    }
    $my_data = sanitize_text_field( $_POST['feature_video_fireworks_field'] );
    update_post_meta( $post_id, '_rj_feature_firwork_video', $my_data );
}
add_action( 'save_post', 'rj_save_firework_feature_video' );

Comments

Popular posts from this blog

How to add image option in nav menu in wordpress

How to add a custom email functionality in woocommerce,wordpress for example new email template for shipping order

How to change user id on checkout page for assign order to different user in woocommerce wordpress