Piklist入门教程八:根据条件显示Meta Fields

Piklist很方便的让你有条件的显示或者隐藏Meta Fields。
在本教程里,我们提供一个radio选择框,来选择显示”Email” text field

  1. 首先我们继续使用教程七的代码,在尾部添加我们field
  2. 加入两个fields:

创建-控制控件
创建一个控制的”subscribe_to_newsletter” radio控件,跟之前创建的控件一样,这个radio用来选择是否显示”newsletter” text控件

piklist('field', array(
    'type' => 'radio'
,'field' => 'subscribe_to_newsletter'
,'label' => 'Would you like to subscribe to our newsletter?'
,'attributes' => array(
        'class' => 'text'
    )
,'position' => 'wrap'
,'choices' => array(
        'yes' => 'Yes'
    ,'no' => 'No'
    )
,'value' => 'no'
));

注意,参数里的value=>no radio的缺省值,也就是判断的条件就yes no。
创建-被控制显示控件

piklist('field', array(
    'type' => 'text'
,'field' => 'email_address'
,'label' => 'Email Address'
,'description' => 'Please enter your email address'
,'position' => 'wrap'
,'conditions' => array(
        array(
         'field' => 'subscribe_to_newsletter'
        ,'value' => 'yes'
        )
    )
));

这个field跟之前创建一样,只是多出一个conditions参数,用一个数值绑定了上面那个radio的值,当值为yes时就显示该text控件

初始默认效果:
conditionally_metabox_no

点选yes后效果:

conditionally_metabox_yes
post-metabox.php全部代码:

<?php
/*
Title: My Post Meta Box
Post Type: post
*/

piklist('field', array(
'type' => 'text'
,'scope' => 'post_meta'
,'field' => 'post_text'
,'label' => 'Text box'
,'description' => 'Field Description'
,'value' => 'Default text'
,'attributes' => array(
        'class' => 'text'
    )
,'position' => 'wrap'
));

piklist('field', array(
    'type' => 'select'
,'scope' => 'post_meta'
,'field' => 'post_select'
,'label' => 'Select box'
,'description' => 'Choose from the dropdown.'
,'attributes' => array(
        'class' => 'text'
    )
,'choices' => array(
        'option1' => 'Option 1'
    ,'option2' => 'Option 2'
    ,'option3' => 'Option 3'
    )
,'position' => 'wrap'
));

piklist('field', array(
    'type' => 'colorpicker'
,'scope' => 'post_meta'
,'field' => 'post_colorpicker'
,'label' => 'Choose a color'
,'value' => '#aee029'
,'description' => 'Click in the box to select a color.'
,'attributes' => array(
        'class' => 'text'
    )
,'position' => 'wrap'
));

piklist('field', array(
    'type' => 'radio'
,'field' => 'subscribe_to_newsletter'
,'label' => 'Would you like to subscribe to our newsletter?'
,'attributes' => array(
        'class' => 'text'
    )
,'position' => 'wrap'
,'choices' => array(
        'yes' => 'Yes'
    ,'no' => 'No'
    )
,'value' => 'no'
));

piklist('field', array(
    'type' => 'text'
,'field' => 'email_address'
,'label' => 'Email Address'
,'description' => 'Please enter your email address'
,'position' => 'wrap'
,'conditions' => array(
        array(
         'field' => 'subscribe_to_newsletter'
        ,'value' => 'yes'
        )
    )
));
文章分类 Piklist, 经验分享 标签: ,

发表评论


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /var/www/wp/code/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048