plugins - WordPress CMB2 - Run function on save

admin2025-06-03  2

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?

Share Improve this question asked Apr 28, 2018 at 20:42 fightstarr20fightstarr20 1,1358 gold badges26 silver badges47 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748960661a315176.html

最新回复(0)