Mayeenul Islam
Mayeenul Islam

Reputation: 4762

How to show conditional custom fields using WordPress CMB2 plugin when a post is added new

I'm a great fan of WordPress CMB2 Plugin while calling custom meta boxes. I came to know that it has a functionality to load a custom field if a condition matches, using its show_on_cb parameter.

I've a scenario:

Product Type: ( ) A   ( ) B   ( ) C  //radio buttons
Field for A:  [                   ]  //textbox
Field for B:  [                   ]  //textbox
Field for C:  [                   ]  //textbox

The process what CMB offers is a PHP way, check a PHP condition, whether of any current state (WordPress Cookie) or a db return.

As I need to activate 'em when on radio button selection, in this way, I can't achieve that, because I can't pass any rule to the show_on_cb parameter that can trigger on radio button selection, and if the function return false, the whole <div> doesn't even showed up (so I can't pass any jQuery to trigger 'em).

How can I solve these:

  1. I need to show respective fields as per radio button selection.
  2. I need to show respective field what the db returns as selected.

Though I know I can achieve that solely with jQuery. I can accept any way using both PHP and jQuery.

Upvotes: 0

Views: 2298

Answers (1)

Mayeenul Islam
Mayeenul Islam

Reputation: 4762

First of all I made a function that only works on edit page - that means the show_on_cb (value: 'show_on_cb' => 'myproducts_product_typeA') will work only if the post is edited, because I used the get_current_screen() to dictate that.

function myproducts_product_typeA( $field ) {
    global $post;
    $screen = get_current_screen();
    if( $screen->action !== 'add' && $screen->post_type == 'my-products' ) {
        $product_type = get_post_meta( $post->ID, 'mp_product_type', TRUE );
        if( $product_type === 'A' ) return 1;
    } else {
        return 1; //to show on add-new page by default
    }
}

So the above function will check the db and return true or false according to fetched data from db, but it will return true only when the post is edited. In new post it won't check the database, and simply return true because I want all the fields to be active then.

Then I'm gonna use jQuery to show/hide my necessary fields as per the radio button selection.

Upvotes: 1

Related Questions