Git Product home page Git Product logo

cmb2-snippet-library's Introduction

CMB2 Code Snippet Library

This is a community-maintained repository of code snippets that help modify the default behavior of CMB2.

Snippets are organized into categories (folders) and each snippet is placed in its own file with a name that describes what it does.

Thank you to the EDD team for the inspiration for this library.

Submitting Your Snippet

We welcome and encourage everyone to submit their code snippets. If you would like to submit your snippet, please fork the repository and then create a pull request.

Please refer to the Contributing guidelines before submitting your pull request.

Proposing a Snippet

If there is a snippet you are unable to find and would like to propose get written, please open an issue and describe your need.

Notes

This is not a tutorial archive. Please see the CMB2 github repo wiki if you're looking for official documentation and tutorials.

These snippets come with no guarantees. Due to the constant evolution of the CMB2 codebase, it is possible that the behavior of these snippets may change overtime. Find something broken? Let us know!

cmb2-snippet-library's People

Contributors

1bigidea avatar arkonisus avatar blobaugh avatar carlosrios avatar danielportoghese avatar davidshq avatar ediamin avatar ericbusch avatar greglancaster71 avatar ipstenu avatar itsmereal avatar jaw-dev avatar jaywood avatar jazzsequence avatar jondcampbell avatar jtsternberg avatar mgratch avatar modemlooper avatar mte90 avatar niklasp avatar pablo-sg-pacheco avatar pilskalns avatar richlloydmiles avatar sioannides avatar strap1 avatar timothyjensen avatar toddmilliken avatar tw2113 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cmb2-snippet-library's Issues

array_key_exists() expects parameter 2 to be array

https://github.com/CMB2/CMB2-Snippet-Library/blob/master/options-and-settings-pages/theme-options-cmb.php#L208

br />
<b>Warning</b>:  array_key_exists() expects parameter 2 to be array, string given in <b>/www/dev.litvurisacxobi.ge/public/themes/wordplate/library/theme-options.php</b> on line <b>313</b><br />
<br />
<b>Warning</b>:  array_key_exists() expects parameter 2 to be array, string given in <b>/www/dev.litvurisacxobi.ge/public/themes/wordplate/library/theme-options.php</b> on line <b>313</b><br />
<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /www/dev.litvurisacxobi.ge/public/themes/wordplate/library/theme-options.php:313) in <b>/www/dev.litvurisacxobi.ge/public/wordpress/wp-includes/option.php</b> on line <b>828</b><br />
<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /www/dev.litvurisacxobi.ge/public/themes/wordplate/library/theme-options.php:313) in <b>/www/dev.litvurisacxobi.ge/public/wordpress/wp-includes/option.php</b> on line <b>829</b><br />

This happens in wp-admin if cmb2 is not loaded, and settings don't exist in db on fresh install.

$opts returned is a string. So instead of using array_key_exists you can simply rely on isset()

screen shot 2017-06-20 at 11 08 26 am

Autocomplete doesn't work if field id starts not from underscore symbol

$cmb->add_field( array(
    'name'       => __( 'Author', 'bt-task' ),    
    'id'         => '_author', // DO WORK
    //'id'         => 'author', DOESN'T WORK
    'type'       => 'autocomplete',
    'options'    => array(
      array('value' => 1, 'name' => 'Admin'),
      array('value' => 2, 'name' => 'Oleg'),
      array('value' => 3, 'name' => 'Grisha')
    )
  ) ); 

Front-End Image Uploads

@jtsternberg A few days ago I ran into the need to get this working in this commit - 8cd6c29

Obviously manage_options was too high, but upload_files is all that's really needed.

However, further exploration into this, if a post is published and the user is creating a 'front-end' edit form of some fashion, we also need to include 'edit_published_posts' as a cap. However this was really an edge case due to me needing to use 'contributors' and not subscribers.

So, the question is actually should we document this stipulation somewhere like here:
https://github.com/WebDevStudios/CMB2-Snippet-Library/blob/master/front-end/cmb2-front-end-wordpress-media-uploader.php#L29

Or just ignore it since it's an edge case...

Autocomplete works only on Post type forms

For example with 'object_types' => array( 'options-page' ) js error comes up:

$(...).autocomplete is not a function

Probably the problem is that plugin's js script runs before jquery-ui-autocomplete.js library is added.

And on post type forms it works because autocomplete library is already there and it's used for adding Tags.

"Notice: Array to string conversion" of multicheck field in own field type

I followed this example: https://github.com/WebDevStudios/CMB2/wiki/Adding-your-own-field-types#example-4-multiple-inputs-one-field-lets-create-an-address-field

Everything works fine until I change type of 'state' field from select to multicheck.

Expected Behavior:

Change select dropdown to multicheck checkboxes.

Actual Behavior:

It throws Notice: Array to string conversion in .../wp-content/plugins/cmb2/includes/types/CMB2_Type_Base.php on line 103

Steps to reproduce (I have confirmed I can reproduce this issue on the trunk branch):

Create custom field type address using this snippet:

https://github.com/WebDevStudios/CMB2-Snippet-Library/blob/master/custom-field-types/address-field-type.php

and change select to multicheck on line 134.

CMB2 Field Registration Code:

add_action( 'cmb2_admin_init', 'yourprefix_register_demo_metabox' );
function yourprefix_register_demo_metabox() {

	$cmb = new_cmb2_box( array(
		// Box Config...
	) );

	$cmb->add_field( array(
		// Field Config...
                'type' => 'address'
	) );
}

Thank you for any help.

Reference: CMB2/CMB2#801

How to get an image field from the options page?

Hi!
First of all, thank you for this awesome plugin :)

I'm trying to get an image field to show from the site options page, but am having some trouble trying to figure out the appropriate code to call it. I'm not sure how to fit your example into the wp_get_attachment_image() function. I've tried..

<?php $image = wp_get_attachment_image( myprefix_get_option( 'footer_image_id', 1 ) ); echo $image ?>
<?php wp_get_attachment_image( myprefix_get_option( 'footer_image_id', 1 )); ?>
<?php wp_get_attachment_image( myprefix_get_option( 'footer_image', 1 )); ?>

And can't seem to get it to work. Please point me in the right direction!

installation

hi, thanks for this addition, i moved from cmb1 to cmb2 and some of my custom fields stopped working. hopefully this library will help. coul you please tell me how/ where i install it, and does it need initialising? thanks

A dropdown for taxonomy terms

Hi
i have read this document for get dropdown taxonomy term
https://github.com/CMB2/CMB2/wiki/Tips-&-Tricks#a-dropdown-for-taxonomy-terms-which-does-not-set-the-term-on-the-post

But this function get all taxonomy (parent children) all togheder

/**
 * Gets a number of terms and displays them as options
 * @param  CMB2_Field $field 
 * @return array An array of options that matches the CMB2 options array
 */
function cmb2_get_term_options( $field ) {
	$args = $field->args( 'get_terms_args' );
	$args = is_array( $args ) ? $args : array();

	$args = wp_parse_args( $args, array( 'taxonomy' => 'category' ) );

	$taxonomy = $args['taxonomy'];

	$terms = (array) cmb2_utils()->wp_at_least( '4.5.0' )
		? get_terms( $args )
		: get_terms( $taxonomy, $args );

	// Initate an empty array
	$term_options = array();
	if ( ! empty( $terms ) ) {
		foreach ( $terms as $term ) {
			$term_options[ $term->term_id ] = $term->name;
		}
	}

	return $term_options;
}

http://imgur.com/a/gBJnm
How can fix this?

Front end forms

I've used CMB2 extensively for additional or custom functions and processes on the back end, but i don't have that same understanding or comfort-level when trying it out for front end applications.

So, I'm in need of some guidance using CMB2 to create front-end forms. I read your New Post Submission Form sample in the Snippet Library, and jcchavezs's cmb2-conditionals but I'm still struggling to get this out there.

Is it possible that you guys could do a front-end form demo with documentation, that doesn't require the use of a shortcode, for something like a registration form with a couple conditional fields?

You guys have been awesome in the past where support was concerned and i'm hoping you can help me out again! :)

Snippet "options-pages-with-tabs-and-submenus" : where is CMB2 2.4.0 ?

The snippet options-pages-with-tabs-and-submenus doesn't work :
It uses tabs feature from an unknown version 2.4.0 of CMB2.
Where is this version ?
Is there a working snippet to add an option page with tabs, with only CMB2 base plugin, and without using cmb2-tabs 3rd party plugin ?

Fields not saving when split_value is true

Thanks for a great add-on field!

Not sure if i'm unique in this issue, but i could use some help...

Using the address field type (w/repeatable), and it saves fine when 'split_value'=>false and it's a serialized single meta_key, but when it's set to true no values get saved, and no meta_keys get created.

It seems like the $value parameter is just not getting passed with meta values with the filter.

Running the latest CMB2 and genesis. Any guidance would be appreciated.

Thanks in advance

Not mainly an issue but lack of information (I can be completely wrong)

I understand that when we create repeatable group data , it saves the in wp_postmeta table in serialized form. But if I try to change / update the section of content (lets say a shortcode in wysiwyg) in bulk as the repeatable data cant be detected by regular like or %like% queries. Even if I try to use regular expressions i am not sure if that works... Any guidance on figuring out with bulk find and replacing of cmb2 repeatable fields will be of great help.
Thank you.

Theme options not saving and retrievig values

Hello,
i have modified CMB2 snippet library Theme options and following code to use on my theme. so i can have accordions or tabs in my theme.

http://arushad.org/how-to-create-a-tabbed-options-page-for-your-wordpress-theme-using-cmb/

and my final code is below, issue is that if i enter some data and save then it is not saving. Form is also generated properly .. See images below.. Please tell me where i am doing wrong. waiting for reply.

    <?php
   /**
    * CMB2 Theme Options  @version 0.1.0
     */   class Euronet_Admin {  
    /**
     * Option key, and option page slug
     * @var string
     */
    private $key = 'euronet_options';  
    /**
     * Options page metabox id
     * @var string
     */
    private $metabox_id = 'euronet_option_metabox'; 
    /**
     * Options Page title
     * @var string
     */
    protected $title = '';
    /**
     * Options Page hook
     * @var string
     */
    protected $options_page = ''; 
    /**
     * Holds an instance of the object
     *
     * @var Myprefix_Admin
     **/
    private static $instance = null; 
    /**
     * Constructor
     * @since 0.1.0
     */
    private function __construct() {
        // Set our title
        $this->title = __( 'Theme Options', 'euronet' );
    }

       /**CMB array **/
        protected $cmb=array();

    /**
     * Returns the running object
     *
     * @return Myprefix_Admin
     **/
    public static function get_instance() {
        if( is_null( self::$instance ) ) {
            self::$instance = new self();
            self::$instance->hooks();
        }
        return self::$instance;
    }

    /**
     * Initiate our hooks
     * @since 0.1.0
     */
    public function hooks() {
        add_action( 'admin_init', array( $this, 'init' ) );
        add_action( 'admin_menu', array( $this, 'add_options_page' ) );
        add_action( 'cmb2_admin_init', array( $this, 'add_options_page_metabox' ) );
        // add_action( 'cmb2_admin_init', array( $this, 'add_counters_metabox' ) );
    }


    /**
     * Register our setting to WP
     * @since  0.1.0
     */
    public function init() {
        register_setting( $this->key, $this->key );
    }

    /**
     * Add menu options page
     * @since 0.1.0
     */
     public function add_options_page() {
        $this->options_page = add_menu_page( $this->title, $this->title, 'manage_options', $this->key, array( $this, 'admin_page_display' ) );  
        // Include CMB CSS in the head to avoid FOUC
        add_action( "admin_print_styles-{$this->options_page}", array( 'CMB2_hookup', 'enqueue_cmb_css' ) );
    }

    /**
     * Admin page markup. Mostly handled by CMB2
     * @since  0.1.0
     */
    public function admin_page_display() {

      $option_tabs = self::add_options_page_metabox(); //get all option tabs
        $tab_forms = array(); 

      echo '<pre>';
          //   print_r($option_tabs);
       echo '</pre>';

        ?>
       <link rel='stylesheet' id='theme_options-css'  href='<?php echo get_stylesheet_directory_uri();  ?>/css/theme_options.css' type='text/css' media='all' />

        <div class="wrap cmb2-options-page <?php echo $this->key; ?>">
            <h2><?php echo esc_html( get_admin_page_title() ); ?></h2>          
      <!--Accordions-->
      <?php foreach($option_tabs as $option_tab) { ?>
         <?php 
       echo '<pre>';
             print_r($option_tab);
       echo '</pre>';
          ?>
          <button class="accordion"><?php echo  $option_tab->meta_box['title'];  ?></button>
          <div class="panel">
            <?php cmb2_metabox_form( $option_tab->meta_box['id'], $option_tab->meta_box['key'] ); ?>
            <div class="clear"></div>
          </div>

      <?php } ?>


      <!--Accordions-->

      <script type="text/javascript">
                var acc = document.getElementsByClassName("accordion");
                var i;

                for (i = 0; i < acc.length; i++) {
                    acc[i].onclick = function(){
                        this.classList.toggle("active");
                        this.nextElementSibling.classList.toggle("show");
                    }
                }
      </script>


        </div>
        <?php
    }

    /**
     * Add the options metabox to the array of metaboxes
     * @since  0.1.0
     */
    function add_options_page_metabox() {


      // Only need to initiate the array once per page-load
         if ( ! empty( $this->option_metabox ) ) {
              return $this->option_metabox;
         }        

        // hook in our save notices
        add_action( "cmb2_save_options-page_fields_{$this->metabox_id}", array( $this, 'settings_notices' ), 10, 2 ); 

    $this->cmb[0] = new_cmb2_box( array(
            'id'         => $this->metabox_id,
      'title'=> 'Language Flags',
            'hookup'     => false,
            'cmb_styles' => false,
            'show_on'    => array(
                // These are important, don't remove
                'key'   => 'options-page',
                'value' => array( $this->key, )
            ),
        ) );

        // Set our CMB2 fields


    $group_field_id = $this->cmb[0]->add_field( array(
    'id'          => 'wiki_test_repeat_group',
    'type'        => 'group',
    'description' => __( 'Generates reusable form entries', 'cmb2' ),
    // 'repeatable'  => false, // use false if you want non-repeatable group
    'options'     => array(
        'group_title'   => __( 'Language {#}', 'cmb2' ), // since version 1.1.4, {#} gets replaced by row number
        'add_button'    => __( 'Add Another Language', 'cmb2' ),
        'remove_button' => __( 'Remove Language', 'cmb2' ),
        'sortable'      => true, // beta
        'closed'     => true, // true to have the groups closed by default
    ),
    ) );

      // Id's for group's fields only need to be unique for the group. Prefix is not needed.
      $this->cmb[0]->add_group_field( $group_field_id, array(
          'name' => 'Language Title',
          'id'   => 'title',
          'type' => 'text',
          // 'repeatable' => true, // Repeatable fields are supported w/in repeatable groups (for most types)
      ) );

      $this->cmb[0]->add_group_field( $group_field_id, array(
          'name' => 'Language Url',
          'id'   => 'url',
          'type' => 'text'         
      ) );

      $this->cmb[0]->add_group_field( $group_field_id, array(
          'name' => 'Language Flag',
          'id'   => 'image',
          'type' => 'file',
      ) );

       $this->cmb[1] = new_cmb2_box( array(
            'id'         => 'number_counters',
      'title' =>'Number Counters',
            'hookup'     => false,
            'cmb_styles' => false,
            'show_on'    => array(
                // These are important, don't remove
                'key'   => 'options-page',
                'value' => array( 'num_counters_mb', )
            ),
        ) );
      $this->cmb[1]->add_field( array(
          'name'    => 'Test Text',
          'desc'    => 'field description (optional)',
          'default' => 'standard value (optional)',
          'id'      => 'wiki_test_text',
          'type'    => 'text',
        ) );

       return $this->cmb;

    }

    /**
     * Register settings notices for display
     *
     * @since  0.1.0
     * @param  int   $object_id Option key
     * @param  array $updated   Array of updated fields
     * @return void
     */
    public function settings_notices( $object_id, $updated ) {
        if ( $object_id !== $this->key || empty( $updated ) ) {
            return;
        }

        add_settings_error( $this->key . '-notices', '', __( 'Settings updated.', 'euronet' ), 'updated' );
        settings_errors( $this->key . '-notices' );
    }

    /**
     * Public getter method for retrieving protected/private variables
     * @since  0.1.0
     * @param  string  $field Field to retrieve
     * @return mixed          Field value or exception is thrown
     */
    public function __get( $field ) {
        // Allowed fields to retrieve
        if ( in_array( $field, array( 'key', 'metabox_id', 'title', 'options_page' ), true ) ) {
            return $this->{$field};
        }

        throw new Exception( 'Invalid property: ' . $field );
      }

     }

     /**
     * Helper function to get/return the Myprefix_Admin object
     * @since  0.1.0
     * @return Myprefix_Admin object
     */
     function euronet_admin() {
    return Euronet_Admin::get_instance();
     }

     /**
     * Wrapper function around cmb2_get_option
     * @since  0.1.0
     * @param  string  $key Options array key
     * @return mixed        Option value
     */
      function euronet_get_option( $key = '' ) {
    return cmb2_get_option( euronet_admin()->key, $key, true );
      }

      // Get it started
      euronet_admin();

Accordion 1 image

image

Accordion 2 image

image

another thing is that i am showing both metabox objects at one page.

Possible issue with 'Dynamically Changing Group Title From Subfield' (row counts are getting off)

I think there is an issue with this snippet, and perhaps more specifically with the below part. Under certain conditions, the Row Numbers get off. One replicatable condition is if you have three rows, delete the third row and add another. That new row should be row 4, but it displaying row 5.

I tried subtracting hidden (aka deleted) rows, but it wasn't working. I tried but my css attribute (visibility) and by the class you assign rows when hidden. Neither worked.

I didn't see this as a known issue. I'd be thrilled if you had a possible solution, as this snippet is particularly useful for what I'm doing. Thank you!
rowindex = $this.parents( '[data-iterator]' ).data( 'iterator' );

changed Save Button

Hello
I am using this code
But I want to change the Save Button
I want to work
This code
<input type="submit" name="step2" id="step2" class="btn_orange" value="<?php _e( 'Continue &rsaquo;&rsaquo;', APP_TD ); ?>" [/>

تور آنتالیا

type select with attribute multiple not working on widget snippet

I tried to set up a this field using the cmb2 widget snippet without luck to get it working

The field definition is:

array(
    'name'        => 'Test',
     'type'        => 'select',
     'multiple'    => true,
     'options'  => array(
         '1'  	=> __( 'Option 1' ),
         '2'  	=> __( 'Option 2' ),
        '3' 	=> __( 'Option 3' )
),

I always got the default value :/

How to retrieve option set in admin

Hi,
I'm having difficulties getting option value set in plugin administration.
Administration uses CMB2 metaboxes to enter values.
I implemented a hook on save_post that should read entered values and do some stuff.
I implemented helper function

function myprefix_get_network_option( $key = '' ) {
    return cmb2_get_option( myprefix_admin()->key, $key );
}

which in my case looks like

 function sipawp_get_option( $key = '' ) {
    return cmb2_get_option($this->prefix,$key);
}

And I don't instantiate admin class as in your example. If I do I get an error "Fatal error: Call to undefined function wp_get_current_user() ..."

I call the sipawp_get_option function from _construct method

$this->sipaapp = sipawp_get_option($this->plugin_slug . '_sipaapp');
$this->sipakey = sipawp_get_option($this->plugin_slug . '_sipakey');

so I could those params in class function, but I receive this error : Fatal error: Call to undefined function cmb2_get_option()

Do you have any thoughts on this ?

Is there any way to use Yoast Seo Analysis for custom meta boxes?

Hello,

Firstly, thank you for your great code!

I just wonder if there is any way to force Yoast Seo Analysis to include text in custom meta boxes? I am using a repeatable group for creating slideshow and all the content of the post is in meta boxes.

Kind Regards,
Oksana

Huge increase in page load time

We are finding issues with the admin options snippet on a site with a large number of posts.

We had a site with 10 woocommerce products and performance was fine.
We added 2,000 new products, and page load time increased alarmingly (from 3 seconds to 10 seconds).
We isolated the issue to the admin options snippet -- with that removed, page load decreased back to 3 seconds or less.

Is there anything in the hooks / underlying library that iterates the posts, and could be causing this?

It only affects the admin options snippet, using CMB for metaboxes on the individual post types is not having this negative impact.

Hope to find help for submenu cpt settings/tabs?

Hallo Guys,

Tried to create a settings page with a submenu(first tab) and multiple tabs/pages but without luck.

So just to clearify:

  • 1 submenu item (settings)
  • multiple metaboxes/tabs (tab1, tab2, tab3)

the problem is as follows the second page tab is also a main menu item.

and if i add 'parent_slug' => 'edit.php?post_type=cpt', to the second tab its also appearing as a submenu.

My code so far:

<?php function prefix_occasions_settings_page() {

	$args = array(
		'id'           => 'prefix_options_page',
		'title'        => 'Settings',
		'object_types' => array( 'options-page' ),
		'parent_slug'  => 'edit.php?post_type=cpt',
		'option_key'   => 'prefix_general_settings',
		'tab_group'    => 'prefix_general_settings',
		'tab_title'    => 'General',
	);

	if ( version_compare( CMB2_VERSION, '2.4.0' ) ) {
		$args['display_cb'] = 'prefix_settings_with_tabs';
	}

	$prefix_general_settings = new_cmb2_box( $args );
	
	$prefix_general_settings->add_field( array(
		'name'    => 'Site Background Color',
		'desc'    => 'field description (optional)',
		'id'      => 'bg_color',
		'type'    => 'colorpicker',
		'default' => '#ffffff',
	) );
	
	$args = array(
		'id'           => 'prefix_settings_page',
		'title'        => 'Second Options',
		'object_types' => array( 'options-page' ),
		'option_key'   => 'prefix_general_settingss',
		'tab_group'    => 'prefix_general_settings',
		'tab_title'    => 'Second',
	);

	if ( version_compare( CMB2_VERSION, '2.4.0' ) ) {
		$args['display_cb'] = 'prefix_settings_with_tabs';
	}
	$prefix_general_settings2 = new_cmb2_box( $args );

	$prefix_general_settings2->add_field( array(
		'name'    => 'Site Background Color',
		'desc'    => 'field description (optional)',
		'id'      => 'bg_color',
		'type'    => 'colorpicker',
		'default' => '#ffffff',
	) );
}
add_action( 'cmb2_admin_init', 'prefix_occasions_settings_page' );

function prefix_settings_with_tabs( $cmb_options ) {
	$tabs = prefix_settings_page_tabs( $cmb_options );
	?>
	<div class="wrap cmb2-options-page option-<?php echo $cmb_options->option_key; ?>">
		<?php if ( get_admin_page_title() ) : ?>
			<h1><?php echo wp_kses_post( get_admin_page_title() ); ?></h1>
		<?php endif; ?>
		<h2 class="nav-tab-wrapper">
			<?php foreach ( $tabs as $option_key => $tab_title ) : ?>
				<a class="nav-tab<?php if ( isset( $_GET['page'] ) && $option_key === $_GET['page'] ) : ?> nav-tab-active<?php endif; ?>" href="<?php menu_page_url( $option_key ); ?>"><?php echo wp_kses_post( $tab_title ); ?></a>
			<?php endforeach; ?>
		</h2>
		<form class="cmb-form" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="POST" id="<?php echo $cmb_options->cmb->cmb_id; ?>" enctype="multipart/form-data" encoding="multipart/form-data">
			<input type="hidden" name="action" value="<?php echo esc_attr( $cmb_options->option_key ); ?>">
			<?php $cmb_options->options_page_metabox(); ?>
			<?php submit_button( esc_attr( $cmb_options->cmb->prop( 'save_button' ) ), 'primary', 'submit-cmb' ); ?>
		</form>
	</div>
	<?php
}

function prefix_settings_page_tabs( $cmb_options ) {
	$tab_group = $cmb_options->cmb->prop( 'tab_group' );
	$tabs      = array();
	foreach ( CMB2_Boxes::get_all() as $cmb_id => $cmb ) {
		if ( $tab_group === $cmb->prop( 'tab_group' ) ) {
			$tabs[ $cmb->options_page_keys()[0] ] = $cmb->prop( 'tab_title' )
				? $cmb->prop( 'tab_title' )
				: $cmb->prop( 'title' );
		}
	}
	return $tabs;
} ?>

Upon Plugin Activation Save Default Settings

We are using CMB2 to create a tabbed plugin admin panel. When a new user installs and activates the plugin they have to manually save the options before they are stored in the database. Do you know of a quick way to save default values so they are immediately available post installation?

[Widget snippet] file (and file_list) field type looks like not working

Hello,
I'm testing this widget class as I'd like to implement a custom widget that allow me to create an array of images to iterate in a customised slider.
I've noticed that, after the installation of this widget as it is, the "upload an image" button do not respond at all when clicking on it.

Any clue or suggestion about how to use this feature?

thx
Paolo

[Widget snippet] Javascript selector error because selector with square brackets

Hi @jtsternberg
I tried to set up follow cmb2 widget snippet (just copy and run).
But error Javascript appear when i click button Add or Upload File::

Uncaught Error: Syntax error, unrecognized expression: label[for=widget-cmb2-widget-boilerplate-slug[2][image]]

I think, should change selector:
From: label[for=widget-cmb2-widget-boilerplate-slug[2][image]]
To: label[for="widget-cmb2-widget-boilerplate-slug[2][image]"]

Array to String conversion error for repeatable groups for front-end submit

In the cmb2-front-end-submit.php example the example for updating post meta is

// Loop through remaining (sanitized) data, and save to post-meta
foreach ( $sanitized_values as $key => $value ) {
    update_post_meta( $new_submission_id, $key, $value );
}

Which work for single values and repeatable groups if they have a value, but if the repeatable groups don't have a value it save an empty array which causes this error

Notice: Array to string conversion in /srv/www/wordpress-develop/src/wp-content/plugins/practical-project-wrangler/admin/helpers/cmb/includes/CMB2_Types.php on line 188

This fixes it by checking if it is an array and if the array is empty it doesn't update the post meta

// Loop through remaining (sanitized) data, and save to post-meta
foreach ( $sanitized_values as $key => $value ) {
    if( is_array( $value ) ) {
        if( !empty( array_filter( $value ) ) ) {
            update_post_meta( $new_submission_id, $key, $value );
        }
    } else {
        update_post_meta( $new_submission_id, $key, $value );
    }
}

Appearance

Is there any easy way apart from creating custom css rules to get the appearance of a settings page to match the look of the WordPress settings pages?

Title throwing error

Im trying this example snippet in my custom theme. I have placed shortcode [cmb_frontend_form] on page and Im getting error on submit with code checking title : There was an error in the submission: Please enter a new title.

// And that the title is not the default title
    if ($cmb->get_field('submitted_post_title')->default() == $_POST['submitted_post_title']) {
        return $cmb->prop('submission_error', new WP_Error('post_data_missing', __('Please enter a new title.')));
    }

When I do not equal !== all is working fine but title can be identical (identical string) with already published (or pending) article :(
Any Idea where to look into?

[options-and-settings-pages] Does not save the settings!

Before start, I need to say that I'm a beginner and my english not so good, but I'll try explain my problem...

I downloaded the snippet that generate a options page and add it on my plugin. After that, I can see and manipulate the menu and the fields of the new options page, but when I click in the save button the page refresh and everything go back to default settings.

https://github.com/WebDevStudios/CMB2-Snippet-Library/tree/master/options-and-settings-pages

I spend a lot of time trying to do this works, but no success! So I Downloaded the "CMB2-Example-Theme" to install and see how it works, but the theme have the same problem on "example options" page...

https://github.com/WebDevStudios/CMB2-Example-Theme

Can someone help me?

Grateful right now and sorry for my bad English! ;-)

Autocomplete Field Type doesn't work if repeating

I set up an autocomplete field type using the example here: https://github.com/WebDevStudios/CMB2-Snippet-Library/blob/master/custom-field-types/autocomplete-field-type.php

Whether I copy and paste this code exactly, or modify it for my own needs, the fields do not work as repeating fields. When you click "add", you get a new row that has only a "remove" button, and no input field. Screenshot:
image

I haven't yet found a way to get the repeating fields to work. Any suggestions for how to do that?

Update widget snippet with working group fields

I am trying to make group fields work at widgets area

First I added a new loop to add group fields correctly:

        public function cmb2( $saving = false ) {

            // Create a new box in the class
            $cmb2 = new CMB2( array(
                'id'      => $this->option_name .'_box', // Option name is taken from the WP_Widget class.
                'hookup'  => false,
                'show_on' => array(
                    'key'   => 'options-page', // Tells CMB2 to handle this as an option
                    'value' => array( $this->option_name )
                ),
            ), $this->option_name );

            foreach ( $this->fields as $field ) {
                if ( ! $saving ) {
                    $field['id'] = $this->get_field_name( $field['id'] );
                }

                $field['default_cb'] = array( $this, 'default_cb' );

                $field_id = $cmb2->add_field( $field );

                // Support for group fields
                if( $field['type'] == 'group' ) {
                    foreach( $field['fields'] as $group_field ) {
                        $cmb2->add_group_field( $field_id, $group_field );
                    }
                }
            }

            return $cmb2;
        }

And the js event to make repeatables working:

(function( window, document, $, cmb ) {
    $( document ).on('widget-updated widget-added', function( event, widget ) {
        var $metabox = $(widget).find('.cmb2-wrap > .cmb2-metabox');
        
        $metabox
            .on('click', '.cmb-add-group-row', cmb.addGroupRow)
            .on('click', '.cmb-add-row-button', cmb.addAjaxRow)
            .on('click', '.cmb-remove-group-row', cmb.removeGroupRow)
            .on('click', '.cmb-remove-row-button', cmb.removeAjaxRow);
    });
})( window, document, jQuery, window.CMB2 );

But I miss something, because i got a duplicated group fields in each group, and also save functionallity is not working

Can someone help me to get it working?

Thanks in advance!

Error on Post Type input value via front-end

Hi there,

I'm attempting to get a submittable form working via the front-end and have implemented the code https://github.com/WebDevStudios/CMB2-Snippet-Library/blob/master/front-end/cmb2-front-end-submit.php as detailed in this tutorial - https://webdevstudios.com/2015/03/30/use-cmb2-to-create-a-new-post-submission-form/.
However, I seem to be having a problem with the post_type value. In the html it is output like so:

<input type="hidden" class="cmb2-hidden" name="atts[post_type]" id="atts[post_type]" value="<br />
<b>Warning</b>:  Parameter 2 to system() expected to be a reference, value given in <b>/srv/www/hideaway-crm.co.uk/htdocs/wp-content/plugins/iweb-core-functionality/lib/meta_box/includes/CMB2_Base.php</b> on line <b>283</b><br />
">

I am using the latest version of WordPress, using the shortcode:
<?php echo do_shortcode( '[cmb-frontend-form id="_cmb_system_form" post_status="publish" post_type="system"]' ); ?> to output my form.

My form does indeed output but due to the post_type field having that error in the value it is causing the code to fail on submitting.

My shortcode functions file looks like this:

/**
 * Gets the front-end-post-form cmb instance
 *
 * @return CMB2 object
 */
function wds_frontend_cmb2_get() {
	// Use ID of metabox in wds_frontend_form_register
	$metabox_id = '_cmb_system_form';
	// Post/object ID is not applicable since we're using this form for submission
	$object_id  = 'fake-object-id';

	// Get CMB2 metabox object
	return cmb2_get_metabox( $metabox_id, $object_id );
}

/**
 * Handle the cmb-frontend-form shortcode
 *
 * @param  array  $atts Array of shortcode attributes
 * @return string       Form html
 */
function wds_do_frontend_form_submission_shortcode( $atts = array() ) {

	// Get CMB2 metabox object
	$cmb = wds_frontend_cmb2_get();
	// Get $cmb object_types
	$post_types = $cmb->prop( 'object_types' );
    $post_type = reset( $post_types );

	// Current user
	$user_id = get_current_user_id();
	// Parse attributes
	$atts = shortcode_atts( array(
		'post_author' => $user_id ? $user_id : 1, // Current user, or admin
		'post_status' => 'publish',
		'post_type'   => '',
		'post_title' => auto_custom_title( '', $post_type ),
	), $atts, 'cmb-frontend-form' );

	debug( $atts );

	/*
	 * Let's add these attributes as hidden fields to our cmb form
	 * so that they will be passed through to our form submission
	 */
	$values = "";
	foreach ( $atts as $key => $value ) {
		$cmb->add_hidden_field( array(
			'field_args'  => array(
				'id'    => "atts[$key]",
				'type'  => 'hidden',
				'default_cb' => $value,
			),
		) );
	}

	// Initiate our output variable
	$output = '';
	// Get any submission errors
	if ( ( $error = $cmb->prop( 'submission_error' ) ) && is_wp_error( $error ) ) {
		// If there was an error with the submission, add it to our ouput.
		$output .= '<h3>' . sprintf( __( 'There was an error in the submission: %s', 'wds-post-submit' ), '<strong>'. $error->get_error_message() .'</strong>' ) . '</h3>';
	}
	// If the post was submitted successfully, notify the user.
	if ( isset( $_GET['post_submitted'] ) && ( $post = get_post( absint( $_GET['post_submitted'] ) ) ) ) {
		// Get submitter's name
		$name = get_post_meta( $post->ID, 'submitted_author_name', 1 );
		$name = $name ? ' '. $name : '';
		// Add notice of submission to our output
		$output .= '<h3>' . sprintf( __( 'Thank you%s, your new post has been submitted and is pending review by a site administrator.', 'wds-post-submit' ), esc_html( $name ) ) . '</h3>';
	}
	// Get our form
	$output .= cmb2_get_metabox_form( $cmb, 'fake-object-id', array( 'save_button' => __( 'Submit Post', 'wds-post-submit' ) ) );
	return $output;
}
add_shortcode( 'cmb-frontend-form', 'wds_do_frontend_form_submission_shortcode' );

with my fields like so:

function wds_frontend_form_register() {

	$prefix = '_cmb_'; // Prefix for all fields

	$system_meta_box = new_cmb2_box( array(
		'id'           => $prefix . 'system_form',
		'title'        => 'System Details',
		'object_types' => array( 'system' ), // Post type
		'hookup'       => false,
		'save_fields'  => false,
	) );

	$system_meta_box->add_field( array(
		'name'    => 'Status',
		'id'      => $prefix . 'system_status',
		'type'    => 'select',
		'options' => array(
			'stock'  => __( 'Stock', 'cmb2' ),
			'wip'    => __( 'WIP', 'cmb2' ),
			'review' => __( 'Review', 'cmb2' ),
			'ready'  => __( 'Ready', 'cmb2' ),
			'live'   => __( 'Live', 'cmb2' ),
		),
	) );
}
add_action( 'cmb2_init', 'wds_frontend_form_register' );

I hope this is enough information to help me with this issue. Would appreciate if someone could get back to me asap as this is urgent.

Many thanks,

Natasha

Improve field style like metabox for admin page

As screenshot
schermata 2016-10-06 alle 12 42 47-fullpage
I have a pure css code of 25 lines that convert the style of the cmb fields in the settings page in that way, what is the best section in this repo for this type of stuff?

List of text input fields

Using some custom PHP code, a list of text input fields (each with a different label) should be generated and displayed to user - the list may change each time the option page is opened.
Values in list should be stored in post as (serialized?) array using this scheme:
$array['input field 1'] = $input_field_1_value;
$array['input field 2'] = $input_field_2_value;
and so on...

Limit-number-of-repeat-groups does not work

This is an automatic translation.

Hello,

Url: CMB2-Snippet-Library/javascript/limit-number-of-repeat-groups.php

I report that the CMB2-Snippet-Library/javascript/limit-number-of-repeat-groups.php script currently generates an error.

By executing an alert: alert("fieldGroupTable = " + fieldGroupTable);

I get the error back:
VM2670 post.php: 777 Uncaught ReferenceError: fieldGroupTable is not defined

WP 4.9.4 - CMB2 2.3.0

Thanks, Claudio

How to

Hi ! Thanks for this plugin, it's totally awesome !

But it's been 2hours i'm playing with two issue :

  • i use the front end submit form example but i cant see the meta boxe in my wp admin and can't edit
    OR
  • I use the front end edit form example but i can't see the meta boxes in my wp admin and can't submit

I thinks that there's something I'm missing.

I'm loading in my functions.php in order :
my users metaboxe file
my submit propertie file
and my property edit file

thx !

address field type

I've noticed with the address field type, if the values are empty, the array keys are still added IF the field type is set to repeatable in the metabox.

This becomes problematical when checking to see if an array is empty or not.
If I'm looping through a repeatable cmb2 metabox that's using an address field for each entry for instance.

Shouldn't the array keys be unset if there's no value in them?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.