在 Wordpress 和 CF7 中从另一个填充 select

Populate a select from another in Wordpress and CF7

我在 Wordpress 中使用 Contact form 7 pugin。我需要用 MySQL 数据库中的 "crops" 填充 Select 字段,并且根据所选的一个,第二个 Select 必须填充此作物的“品种.

我知道使用CF7条件田是可以的,但是有53种作物和400多个品种。因此,数据库和联系表中会有很多字段。

我认为应该使用ajax来完成,但我对此一无所知,而且我找不到任何示例来学习使用ajax + CF7 + Wordpress。 我想做的是查询 MySQL (Select variedad from cultivos where cultivo = 'id_cultivo') 并用结果填充 select。

有人知道我该怎么做吗?

I need to populate a Select field with "crops" that are in a MySQL DB

使用 Smart Grid plugin extension for CF7 中的动态下拉字段。

它允许您使用一组现有的 post 或分类法来填充您的下拉列表,否则它也可以使用挂钩来填充,因此您可以构建自定义 sql如果您的 'crops' 属于自定义 table.

and depending of the chosen one, a second Select has to be populated with this crop's "variety.

所以这更棘手。使用分类法填充的动态下拉列表允许您构建 jquery select2 下拉列表,这使得搜索长选项列表变得更加容易,此外,如果您的分类法是分层的(2 级深),它将使用父级术语作为下拉列表中的选项组,实际选项将是子术语。因此,您可以将 'crops' 和 'varieties' 组织为父项->子项的分类法。没有品种的农作物本身就是品种,您的下拉菜单将允许用户 select 特定类别中的品种。

这样可以更轻松地在您的表单上进行设置,而无需隐藏下拉菜单。它也更具可扩展性和可维护性,因为每当您更新 crop/variety 条款时,它都会动态反映在表单中,而无需更改您的表单。

我希望以上所有内容都有意义。如果您想进一步探索这一点,可以在插件支持论坛上 post。

为了解决我的问题,我做了以下几行:

在js文件中:

    jQuery(document).ready(function($) {
     $("#idsubfamilia").change(function(e) {


                 e.preventDefault();
         jQuery.post(MyAjax.url, {action : 'buscar_posts' ,cadena : $('#idsubfamilia').val() }, function(response) {
//                $('#variedad_container').hide().html(response).fadeIn();
$('#variedad_container').hide().html(response).fadeIn();
            });
    });

});

在functions.php(感谢http://masquewordpress.com/como-utilizar-ajax-correctamente-en-wordpress/):

/* AJAX */

// Primero incluimos nuestro archivo javascript definido anteriormente
wp_enqueue_script( 'mi-script-ajax',get_bloginfo('stylesheet_directory') . '/js/ajax-search.js', array( 'jquery' ) );

// ahora declaramos la variable MyAjax y le pasamos el valor url (wp-admin/admin-ajax.php) al script ajax-search.js
wp_localize_script( 'mi-script-ajax', 'MyAjax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );

//Para manejar admin-ajax tenemos que añadir estas dos acciones.
//IMPORTANTE!! Para que funcione reemplazar "buscar_posts" por vuestra action definida en ajax-search.js

add_action('wp_ajax_buscar_posts', 'buscar_posts_callback');
add_action('wp_ajax_nopriv_buscar_posts', 'buscar_posts_callback');

function buscar_posts_callback() {

        global $wpdb;
    $subfamilia=$_POST['cadena'];
    //$datos = $wpdb->get_results('SELECT id, subfamilia_' . $idioma . ' FROM wp_custom_subfamilias  ORDER BY subfamilia_' . $idioma);
    $datos = $wpdb->get_results("SELECT variedad FROM wp_custom_variedad where subfamilia_fk='".$subfamilia."' ORDER BY variedad");

     echo '<ul>';
echo '<select name="selectVariedad" id="idSelectVariedad">';
    foreach ($datos as $dato) {


       echo "<option value='".$dato->variedad."'>".$dato->variedad."</option>";


    }
echo '</select>';
     echo '</ul>';
    die(); // Siempre hay que terminar con die

}