添加新 post 时如何使用 WordPress CMB2 插件显示条件自定义字段

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

我是 WordPress CMB2 Plugin while calling custom meta boxes. I came to know that it has a functionality 的超级粉丝,如果条件匹配,使用其 show_on_cb 参数加载自定义字段。

我有一个场景:

产品类型:( ) A ( ) B ( ) C //单选按钮
A 的字段:[ ] // 文本框
B 字段:[ ] //文本框
C的字段:[]//文本框

CMB 提供的过程是一种 PHP 方式,检查 PHP 条件,无论是任何当前状态(WordPress Cookie)还是数据库 return.

因为我需要在选择单选按钮时激活它们,所以我无法实现,因为我无法将任何规则传递给可以在单选按钮上触发的 show_on_cb 参数按钮选择,如果函数 return false,整个 <div> 甚至都没有出现(所以我不能传递任何 jQuery 来触发它们)。

我该如何解决这些问题:

  1. 我需要根据单选按钮选择显示相应的字段。
  2. 我需要显示各个字段选择的数据库 returns。

虽然我知道我可以单独使用 jQuery 来实现。我可以接受使用 PHP 和 jQuery 的任何方式。

首先,我创建了一个仅适用于 edit 页面的函数 - 这意味着 show_on_cb(值:'show_on_cb' => 'myproducts_product_typeA')仅在 post 时才有效已编辑,因为我使用 get_current_screen() 来指示。

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
    }
}

所以上面的函数会根据从db中获取的数据检查db和return truefalse,但是它会return true仅当 post 被编辑时。在新的 post 中,它不会检查数据库,只是 return true 因为我希望所有字段都处于活动状态。

然后我将根据单选按钮选择使用 jQuery 到 show/hide 我的必要字段。