How do metaboxes work (saving the data and displaying it on front end?)

I’m using the cmb2 plugin and am struggling to make it save my data and display it on the front end.

My code for the functions.php file of the plugin:

add_action( ‘cmb2_init’, ‘cmb2_listingpro’ );

function cmb2_listingpro() {
$prefix = ‘_listingpro_’;
$cmb = new_cmb2_box([
‘id’ => ‘listingpro_dates’,
‘title’ => __( ‘Dates Listing is Available’, ‘cmb2’ ),
‘object_types’ => array( ‘listing’, ),
‘context’ => ‘advanced’,
‘priority’ => ‘high’,
‘show_names’ => true,
]);

$cmb_group_id = $cmb->add_field([
‘id’ => ‘dates’,
‘type’ => ‘group’,
‘options’ => [
‘group_title’ => __(‘Dates {#}’, ‘text_domain’),
‘add_button’ => __(‘New Date’, ‘text_domain’),
‘remove_button’ => __(‘Remove Date’, ‘text_domain’)
]
]);

$cmb->add_group_field($cmb_group_id, [
‘name’ => ‘Test Date Picker’,
‘id’ => ‘date_text’,
‘type’ => ‘text_date’,
]);

The site has a ‘create a new listing page’ and ‘edit listing page’.
I’ve added this code to files that control both pages:

global $listingpro_options;
$object_id = 2;
$metabox_id = ‘listingpro_dates’;
$mylisting = cmb2_metabox_form( ‘listingpro_dates’, $object_id );

The problem with these pages is that the data won’t save. Am I missing something here?

Finally, on the page that displays the final listing, I’ve added this code to the php file to display the data from the metabox.

add_action(‘init’, ‘listingpro_dates2’, 0 );

function listingpro_dates2() {
$term_id = get_queried_object()->term_id;
$dateslist = get_term_meta( $term_id, ‘_listingpro_dates’, true );
if ( is_category() ) {
if ( $dateslist ) {
echo $dateslist;
}
}

}

Nothing from the metabox shows up on this page. Maybe because the data isn’t saving?
Also, I’m not too sure if I used the $tag/hook of the add_action() function correctly.

Any help is greatly appreciated. Thanks.

Read more here:: How do metaboxes work (saving the data and displaying it on front end?)

Leave a Reply

Your email address will not be published. Required fields are marked *