Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellenmace/5ce7891ce57d7600dea7ffec7f717910 to your computer and use it in GitHub Desktop.
Save kellenmace/5ce7891ce57d7600dea7ffec7f717910 to your computer and use it in GitHub Desktop.
How to create CMB2 custom fields in the WP admin
<?php
/*
The exmaple below shows how to create a metabox with three fields in it that is displayed in the
create/edit post admin screens for the 'badge' and 'post' post types.
Make sure you're activated the CMB2 plugin, or used code similar to this to make sure CMB2 is being loaded:
if ( file_exists( dirname( __FILE__ ) . '/cmb2/init.php' ) ) {
require_once dirname( __FILE__ ) . '/cmb2/init.php';
} elseif ( file_exists( dirname( __FILE__ ) . '/CMB2/init.php' ) ) {
require_once dirname( __FILE__ ) . '/CMB2/init.php';
}
See this file on GitHub for lots more examples: https://github.com/WebDevStudios/CMB2/blob/master/example-functions.php
*/
function wds_add_custom_fields_in_admin() {
$prefix = '_rth_badge_';
$badge_metabox = new_cmb2_box( array(
'id' => $prefix . 'metabox',
'title' => __( 'Details', 'text-domain' ),
'object_types' => array( 'badge', 'post' ), // Enter the post type slugs you want these fields to apply to here.
) );
$badge_metabox->add_field( array(
'name' => __( 'Miles Required (Year)', 'text-domain' ),
'desc' => __( 'The minimum number of miles needed to earn this badge.', 'text-domain' ),
'id' => $prefix . 'miles_required',
'type' => 'text_small',
'attributes' => array(
'type' => 'number',
'min' => '0',
),
) );
$badge_metabox->add_field( array(
'name' => __( 'Medal', 'text-domain' ),
'desc' => __( 'Mark this badge as a medal.', 'text-domain' ),
'id' => $prefix . 'is_medal',
'type' => 'checkbox',
) );
$badge_metabox->add_field( array(
'name' => __( 'Image', 'text-domain' ),
'desc' => __( 'Image to be displayed when the runner has earned this badge.', 'text-domain' ),
'id' => $prefix . 'image',
'type' => 'file',
'options' => array(
'url' => false,
),
'text' => array(
'add_upload_file_text' => 'Add Image',
),
) );
}
add_action( 'cmb2_admin_init', 'wds_add_custom_fields_in_admin' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment