Steve Taylor
Steve Taylor

Reputation: 1951

multiple show_on restrictions for CMB2

I'm just getting going with the CMB2 plugin. As far as I can tell, there's no way of applying multiple restrictions to a box. There's limiting by post type, and the two built-in show_on conditions (as per Display Options, and you can add custom show_on conditions. But when it comes to show_on, you can only pass one array with a key/value pair. I've tried passing an array of arrays and it doesn't seem to work, e.g.:

$cmb = new_cmb2_box( array(
    'id'                => 'slideshow_content_box',
    'title'             => __( 'Slideshow content' ),
    'object_types'      => array( 'page' ),
    'show_on'   => array(
        array(
            'key'       => 'id',
            'value'     => array( 30 )
        ),
        array(
            'key'       => 'page-template',
            'value'     => 'page_template.php'
        ),
    ),
    'context'           => 'normal',
    'priority'          => 'high',
    'show_names'        => true,
    'closed'            => false,
));

I've tried hacking this with the cmb2_show_on filter, but custom arguments seem to get stripped out.

Is there a way of combining multiple show_on restrictions?

Upvotes: 3

Views: 1689

Answers (1)

J. Walkley
J. Walkley

Reputation: 13

I'm guessing this should be closed but for any continued viewers you can add a function via 'show_on_cb' to define conditions.

Your solution would be something like:

$cmb = new_cmb2_box( array(
    'id'                => 'slideshow_content_box',
    'title'             => __( 'Slideshow content' ),
    'object_types'      => array( 'page' ),
    'show_on_cb'        => 'add_conditions',
    'context'           => 'normal',
    'priority'          => 'high',
    'show_names'        => true,
    'closed'            => false,
));

//Return true if page template is 'page-template' or id is 30.
function add_conditions() {
    $page_template = get_page_template();
    $page_id = get_the_id();

    if ( $page_template === 'page-template' || $page_id === 30 ) {
        return true;
    }
    return false;
}

There's more show_on documentation here but it is extensive so it might be confusing.

Upvotes: 1

Related Questions