【问题标题】:Gravity Forms get product choices label and value ONLYGravity Forms 仅获得产品选择标签和价值
【发布时间】:2022-12-10 19:05:32
【问题描述】:

我有一个字段 ID 为 7 的产品字段,我已经向它添加了选项;也就是下图: Image

我能够像 $entry['7'] 那样拉出选定的字段,但响应伴随着价格 -> Toyota|30 或 Toyota @30

  1. 我如何只获得标签 --> Toyota

  2. 我如何只获得价值 --> 20000

    在此先感谢您的帮助。

【问题讨论】:

    标签: wordpress gravity-forms-plugin gravityforms


    【解决方案1】:

    在为此苦苦挣扎了一个多小时之后,似乎没有任何方法可以直接从 Gravity Forms 获得它。你可能不再需要它了,但也许它会节省别人的时间。

    在我的例子中,我需要一些方法来获取这个值并在提交条目之前使用它进行验证,所以我使用了钩子gform_validation

    你最好的选择,也是我最终决定的,是使用 Gravity Forms 返回的值来找到你想要的文本

    add_filter('gform_validation', 'price_validation', 10, 2);
    function price_validation($validation_result, $context){
        $form = $validation_result['form'];
    
        foreach ($form['fields'] as $field ){
            //Find our product field.
            if ($field->type == 'product'){
                //Explode useless Gravity Forms string into array.
                $value = explode('|', rgpost("input_{$field->id}"));
    
                //Get the product choices.
                $choices = $field->choices;
                //Find the key of the chosen option.
                $key = array_search($value[0], array_column($choices, 'value'));
                //Get the text of this option.
                $text = $choices[$key]['text'];
    
                //Make array with all values obtained.
                $value = array(
                    'text' => $text,
                    'value' => $value[0],
                    'price' => number_format($value[1], 2, ',', ' '),
                );
    
                //Use $value for whatever you want.
            }
        }
    
        $validation_result['form'] = $form;
        return $validation_result;
    }
    

    或者,如果您只需要价格:

    $value = rgpost("input_{$field->id}");
    if (($pos = strpos($value, "|")) !== false) {
        $price = number_format(substr($value, $pos + 1), 2, ',', ' ');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 2019-07-09
      相关资源
      最近更新 更多