2

我需要在 WP 中创建两个链式选择输入(国家、城市)。(所有都在位置分类中,国家是主要类别,城市是子类别)

在第一个选择中,我列出了所有国家:

$locations = get_terms( ‘locations’, array(
‘hide_empty’ => false,
‘parent’ => 0 ) );

在第二个选择中,我只需要取决于所选国家/地区的城市(无需页面刷新/提交,因此使用 AJAX)

我需要将选定值从第一个选择传递给 php 变量:

$whichCountry = AJAX RESPONSE HERE

列出第二个选择:

$locations = get_terms( ‘locations’, array(
‘hide_empty’ => false,
‘parent’ => $whichCounty) );

请帮助我如何实现这一点,我制作了相同的代码,但还不够:

JS:

(function ($) {
$(document).ready(function () {
$(‘#first_select’).on(‘change’, function(){
$.post(
PT_Ajax.ajaxurl,
{
// wp ajax action
action: ‘ajax-inputtitleSubmit’,

// vars
data: $(‘#first-select’).val(),

// send the nonce along with the request
nextNonce: PT_Ajax.nextNonce
},
function (response) {
console.log(response.data);
}
);
return false;
});

});
})(jQuery);

PHP:

add_action( ‘wp_enqueue_scripts’, ‘inputtitle_submit_scripts’ );
add_action( ‘wp_ajax_ajax-inputtitleSubmit’, ‘myajax_inputtitleSubmit_func’ );
add_action( ‘wp_ajax_nopriv_ajax-inputtitleSubmit’, ‘myajax_inputtitleSubmit_func’ );

function inputtitle_submit_scripts() {

wp_enqueue_script( ‘inputtitle_submit’, get_template_directory_uri() . ‘/assets/js/inputtitle_submit.js’, array( ‘jquery’ ) );
wp_localize_script( ‘inputtitle_submit’, ‘PT_Ajax’, array(
‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ),
‘nextNonce’ => wp_create_nonce( ‘myajax-next-nonce’ )
)
);

}

function myajax_inputtitleSubmit_func() {
// check nonce
$nonce = $_POST[‘nextNonce’];
if ( ! wp_verify_nonce( $nonce, ‘myajax-next-nonce’ ) ) {
die ( ‘Busted!’ );
}

// generate the response
$response = json_encode( $_POST );

// response output
header( “Content-Type: application/json” );
$whichCountry = $response;

// IMPORTANT: don’t forget to “exit”
exit;

}

函数.php

include_once(‘inputtitle_submit_inc.php’)
4

0 回答 0