I am using CMB2 to add basic metabox in WordPress like this..
add_action( 'cmb2_admin_init', 'cmb2_sample_metaboxes' );
function cmb2_sample_metaboxes() {
$prefix = '_yourprefix_';
$cmb = new_cmb2_box( array(
'id' => 'test_metabox',
'title' => __( 'Test Metabox', 'cmb2' ),
'object_types' => array( 'page', ),
'context' => 'normal',
'priority' => 'high',
'show_names' => true,
) );
$cmb->add_field( array(
'name' => __( 'Test Text', 'cmb2' ),
'desc' => __( 'field description (optional)', 'cmb2' ),
'id' => $prefix . 'text',
'type' => 'text',
'show_on_cb' => 'cmb2_hide_if_no_cats',
) );
}
Everything works great but I am trying to run a custom function when the values are saved.
I have found the function after_save - //source-class-CMB2.html#804
But I am struggling to work out how to hook into it and run my own function. Anyone done anything similar?
I am using CMB2 to add basic metabox in WordPress like this..
add_action( 'cmb2_admin_init', 'cmb2_sample_metaboxes' );
function cmb2_sample_metaboxes() {
$prefix = '_yourprefix_';
$cmb = new_cmb2_box( array(
'id' => 'test_metabox',
'title' => __( 'Test Metabox', 'cmb2' ),
'object_types' => array( 'page', ),
'context' => 'normal',
'priority' => 'high',
'show_names' => true,
) );
$cmb->add_field( array(
'name' => __( 'Test Text', 'cmb2' ),
'desc' => __( 'field description (optional)', 'cmb2' ),
'id' => $prefix . 'text',
'type' => 'text',
'show_on_cb' => 'cmb2_hide_if_no_cats',
) );
}
Everything works great but I am trying to run a custom function when the values are saved.
I have found the function after_save - https://cmb2.io/api//source-class-CMB2.html#804
But I am struggling to work out how to hook into it and run my own function. Anyone done anything similar?
If you haven't gotten the answer to this yet, I found the answer by sifting through the source code. I was able to hook into the post save event by using: cmb2_save_{$object_type}_fields_{$cmb_id}
. This hook fires whenever you save a certain object type with a specific metabox ID.
So, in your case your $cmb_id
is test_metabox
, and $object_type
will be page
.
Hooking in would look something like this:
add_action( 'cmb2_save_page_fields_test_metabox', 'my_post_save_function', 10, 3 );
function my_post_save_function( string $object_id, array $updated, CMB2 $cmb )
{
// code
}
The docblock in the source is messed up, I corrected the parameter types above: Source