PHP code example of abuyoyo / cmb2-switch-button

1. Go to this page and download the library: Download abuyoyo/cmb2-switch-button library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

abuyoyo / cmb2-switch-button example snippets


add_action( 'cmb2_admin_init', 'create_your_metabox' );
if(!function_exists('create_your_metabox')){
  function create_your_metabox(){
    $prefix = '_slug_';

    $cmb2_metabox = new_cmb2_box( array(
        'id'            => $prefix . 'test_metabox',
        'title'         => esc_html__( 'Test Metabox', 'tmv' ),
        'object_types'  => array( 'page'), // Post type
        'priority'   => 'high',
        'context'    => 'normal',
    ) );

    $cmb2_metabox->add_field( array(
        'name'             => esc_html__( 'Dynamically Load', 'text-domain' ),
        'id'               => $prefix . 'metabox_id',
        'desc'             => esc_html__('','text-domain'),
        'type'	           => 'switch',
        'default'          => true, //If it's checked by default 
        'active_value'     => true,
        'inactive_value'   => false
    ) );
  }
}

$test_meta = get_post_meta($post->ID, '_slug_metabox_id', true);

if($test_meta){
  //Do something when it's checked;
}

$test_meta = get_post_meta($post->ID, '_slug_metabox_id', true);

if($test_meta === 'enable'){
  //Do something when it's checked;
}else{
  //Do something when it's unchecked;
}