Skip to content

Instantly share code, notes, and snippets.

@chrono-meter
Last active October 7, 2019 09:08
Show Gist options
  • Save chrono-meter/225ee7a59af96775dbcfd0de0f01fbca to your computer and use it in GitHub Desktop.
Save chrono-meter/225ee7a59af96775dbcfd0de0f01fbca to your computer and use it in GitHub Desktop.
<?php
/**
* CMB2 delete value instead of saving empty value. So fields with default value cannot hold empty value.
* This example works around this issue by adding new field parameter `initial value'.
*
* Example:
* $cmb->add_field( array(
* 'name' => 'Title for publish',
* 'initial_value' => '%d product(s) published',
* 'id' => 'title_publish',
* 'type' => 'text',
* ) );
*
* @link https://gist.github.com/chrono-meter/225ee7a59af96775dbcfd0de0f01fbca
*/
class Cmb2_initial_value {
function __construct() {
add_action( 'cmb2_before_field_row', array( $this, 'cmb2_before_field_row' ) );
add_action( 'cmb2_after_field_row', array( $this, 'cmb2_after_field_row' ) );
}
/**
* @param CMB2_Field $field The current field object.
*/
function cmb2_before_field_row( $field ) {
$field_type = $field->type();
add_filter( "cmb2_types_esc_{$field_type}", array( $this, 'cmb2_types_esc' ), 10, 4 );
}
/**
* @param CMB2_Field $field The current field object.
*/
function cmb2_after_field_row( $field ) {
$field_type = $field->type();
remove_filter( "cmb2_types_esc_{$field_type}", array( $this, 'cmb2_types_esc' ), 10 );
}
/**
* @param mixed $override_value Escaping override value to return. Default: null. false to skip it.
* @param mixed $meta_value The value to be output.
* @param array $field_args The current field's arguments.
* @param object $field This `CMB2_Field` object.
*
* @return mixed
*
* @see CMB2_Field::escaped_value()
*/
function cmb2_types_esc( $override_value, $meta_value, $field_args, $field ) {
if ( isset( $field_args['initial_value'] ) ) {
return get_post_status( $field->object_id ) == 'auto-draft' ? $field_args['initial_value'] : $meta_value;
}
return $override_value;
}
}
new Cmb2_initial_value();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment