有可能得到主题定制选项的标签吗?

时间:2016-12-24 作者:Guitaro

我有以下代码供自定义程序添加一些选择选项:

$wp_customize->add_setting( \'price1\', array(\'default\'=>\'95\'));
  $wp_customize->add_control( \'price1\', array(
    \'label\' => \'price 1\',
    \'settings\' =>  \'price1\',
    \'section\' => \'pricessection\',
    \'type\'     => \'select\',
        \'choices\'  => array(
            \'reguler price\'  => \'95\',
            \'special price\' => \'65\',
            \'other price\' => \'35\',
        ),
) );
现在如果我用这个:

echo get_theme_mod( \'price1\' );
在我的主题中,我将获得所选选项的值。

我还希望能够获取所选选项的标签(而不是设置的标签)。有可能吗?怎样

Or in other words:我如何回应“其他价格”以及如何回应“35”?

1 个回复
SO网友:Weston Ruter

如果自定义程序已引导(即customize_register 动作已启动),然后您可以查看控件本身(假设您翻转choices 数组,因为我认为您的值应该是键,反之亦然):

$price = $wp_customize->get_setting( \'price1\' )->value();
$control = $wp_customize->get_control( \'price1\' );
$price_text = $control->choices[ $price ];
然而,您可能希望在外部获取所选价格的文本,即使定制程序没有启动。在这种情况下,您应该单独存储choices数组,然后将其作为choices 但也可以在其他地方重用它。例如:

$wpse_250302_default_price_choice = \'95\';
$wpse_250302_price_choices = array(
    \'95\' => \'regular price\',
    \'65\' => \'special price\',
    \'35\' => \'other price\',
);

add_action( \'customize_register\', function( WP_Customize_Manager $wp_customize ) {
    global $wpse_250302_default_price_choice, $wpse_250302_price_choices;

    $wp_customize->add_setting( \'price1\', array(
        \'default\' => $wpse_250302_default_price_choice,
    ) );

    $wp_customize->add_control( \'price1\', array(
        \'label\' => \'price 1\',
        \'settings\' => \'price1\',
        \'section\' => \'pricessection\',
        \'type\' => \'select\',
        \'choices\' => $wpse_250302_price_choices,
    ) );
} );

add_action( \'wpse_250302_some_theme_action\', function() {
    global $wpse_250302_default_price_choice, $wpse_250302_price_choices;
    $price_value = get_theme_mod( \'price1\', $wpse_250302_default_price_choice );
    $price_text = $wpse_250302_price_choices[ $price_value ];
    printf( "<h4>%s: %s</h4>", esc_html( $price_text ), esc_html( $price_value ) );
} );

相关推荐