Last active
June 8, 2017 18:56
-
-
Save carasmo/b3f75174b78dcc39953f14544d6186b1 to your computer and use it in GitHub Desktop.
Add field with CMB2 to a CPT and show it in Genesis Entry Content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment