简体   繁体   English

将重力窗体中的字段连接到WooCommerce中的字段

[英]Connect a field in Gravity Forms to a field in WooCommerce

I want to build a Gravity form where the user can search all products via an Ajax search. 我想构建一个Gravity表单,用户可以在其中通过Ajax搜索来搜索所有产品。 That search box has to be connected to the "Product title" field in WooCommerce. 该搜索框必须连接到WooCommerce中的“产品标题”字段。

So when the user types the first letter (ex.: PIN) in the Gravity form search box, the Ajax dropdown shows the 2 book titles available in the database: "PINNOCHIO" and "PINNOCHIO RETURNS", for example. 因此,当用户在重力形式搜索框中键入第一个字母(例如:PIN)时,Ajax下拉列表将显示数据库中可用的2个书名:例如“ PINNOCHIO”和“ PINNOCHIO RETURNS”。 Then the user selects a title that he's interested in and then submits the form. 然后,用户选择他感兴趣的标题,然后提交表单。

I have no idea how to connect a field in Gravity to a field in WooCommerce. 我不知道如何将Gravity中的字段连接到WooCommerce中的字段。 Can it be done? 能做到吗

You'll need to add some code to dynamically populate the dropdowns. 您需要添加一些代码来动态填充下拉列表。 Here is the official documentation for it: https://docs.gravityforms.com/dynamically-populating-drop-down-fields 这是它的官方文档: https : //docs.gravityforms.com/dynamically-populating-drop-down-fields

If I take their starting point and reconfigure it to work with Products, it would look like this: 如果我以他们的出发点并重新配置它以与产品一起使用,它将看起来像这样:

add_filter( 'gform_pre_render_51', 'populate_posts' );
add_filter( 'gform_pre_validation_51', 'populate_posts' );
add_filter( 'gform_pre_submission_filter_51', 'populate_posts' );
add_filter( 'gform_admin_pre_render_51', 'populate_posts' );
function populate_posts( $form ) {

    foreach ( $form['fields'] as &$field ) {

        if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-products' ) === false ) {
            continue;
        }

        $posts = get_posts( array(
            'post_type' => 'product',
            'numberposts' => -1,
        ) );

        $choices = array();

        foreach ( $posts as $post ) {
            $choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
        }

        // update 'Select a Product' to whatever you'd like the instructive option to be
        $field->placeholder = 'Select a Product';
        $field->choices = $choices;

    }

    return $form;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM