carasmo
4/17/2017 - 11:32 PM

Add field with CMB2 to a CPT and show it in Genesis Entry Content

Add field with CMB2 to a CPT and show it in Genesis Entry Content

<?php
// don't add twice

// 1. this adds the metabox and field to the CPT tesimonial (see CMB2 docs). Requires CMB2.

/**
 * 
 * Add Testimonial Author Metabox and Field
 *
 */
function yourprefix_add_testimonial_author_metabox_field() {

	$prefix = '_cmb_';

	$cmb = new_cmb2_box( array(
		'id'            => $prefix . 'testimonial_author_mb',
		'title'         => __( 'Testimonial Author (required)', 'your-text-domain' ),
		'object_types'  => array( 'testimonial' ), //* Post types
		'context'       => 'top',
		'priority'      => 'high',
		'show_names'    => false, 
		'closed'        => false,
	) );
            
            
	$cmb->add_field( array(
		'name'       => __( 'Testimonial Author (required)', 'your-text-domain' ),
		'id'         => $prefix . 'testimonial_author',
		'type'       => 'text',
		'cmb_styles' => false, 
		'attributes' => array(
			'style'    => 'width:100%;padding:5px;font-size:16px;',
			'required' => 'required',
		),        
	) );
	
} 
add_action( 'cmb2_admin_init', 'yourprefix_add_testimonial_author_metabox_field' );


// 2. shows the text entered in the field in the single, archive and taxonomies for the testimonial post type.

/**
 * 
 * Callback / Display Testimonial Author Field
 *
 */
function yourprefix_display_testimonial_author_entry_content() {

	if( ! in_array( get_post_type(), array( 'testimonial' ) ) ) return;
	//exit if not testimonial single, archive, or taxonomy
	
	$prefix = '_cmb_';
	$testimonial_author = get_post_meta( get_the_ID(), $prefix . 'testimonial_author', true );

	if ( ! empty( $testimonial_author ) )  :
	
		echo '<p class="testimonial-author"><em>' . $testimonial_author . '</em></p>';
	
	endif; //not empty testimonial_author
	

}
add_action( 'genesis_entry_content', 'yourprefix_display_testimonial_author_entry_content', 15 );