如何在Wordpress中使用表单将ajax请求发送至php函数,然后将该函数的返回值(永久链接至帖子)发送回我的ajax函数响应,以打开针对该特定帖子的新标签页?
我在functions.php
中的php函数:
function zip_search($userZip){
$args = array(
'posts_per_page' => -1,
'post_type' => 'Locations'
);
$wp_query = new WP_Query($args);
if( $wp_query->have_posts() ): while( $wp_query->have_posts() ) : $wp_query->the_post();
$zipField=get_field('zip_codes_services');
$zipString = $zipField . ', ';
$array = explode(', ' , $zipString); //split string into array seperated by ', '
foreach($array as $value) //loop over values
{
if($value==$userZip){
$post_id = get_the_ID();
$permalink=get_permalink($post_id);
return ($permalink); //print
}
}
endwhile;
wp_reset_postdata();
endif;
}
我的表格,在我网站的首页上:
<form id="zip_search_form" action="" method="post"><input class="form-control search-input" autocomplete="off" name="zipcode" type="text" value="" placeholder="Enter Zip Code" /></form><input type="submit" />
我尝试过的Javascript
$("form#zip_search_form").on("submit", function(event) {
$('form#zip_search_form .clear-button').addClass('active');
event.preventDefault();
all_locations_map_ajax_filter();
});
//Our main ajax call
function zip_search_ajax_filter(){
var filters = [];
var zipcode = $('form#zip_search_form input[name="zip_search"]').val();
//process the form
$.ajax({
type: "POST", // define the type of HTTP verb we want to use (POST for our form)
dataType : "json",
url: ajaxcall.ajaxurl,
data: {
"action": "zip_search", //calls the function in the functions.php file
"zipcode": zipcode
},
success: function(response) {
if(response.length > 0){
//remove the current markers
$(this).html(response)
}
}
})}
我很幸运地尝试更改Javascript。我将其包含在名为js
的文件夹scripts.js
中。我已经尝试阅读AJAX文档,但是我不确定该如何获取表单数据等,或者我应该将其确切放置在文件结构中的位置。任何建议表示赞赏。