【发布时间】:2018-09-22 22:11:58
【问题描述】:
我实现了我的自定义帖子类型,并且内容以这种方式在 while 循环中列在我的页面上:
$args = array('post_type' => 'studien', 'order' => 'ASC', 'posts_per_page' => 4 );
$loop = new WP_Query($args);
if($loop->have_posts()):
while($loop->have_posts()) : $loop->the_post();?>
<div class="col-md-6">
// data are listed here
</div>
<?php endwhile;
endif;
?>
在我的提交中,我尝试根据一些自定义分类法过滤数据:
$ = jQuery;
var search = $("#search-studien");
var searchForm = search.find("studien");
$(document).ready(function () {
$('#studien').submit(function (evt) {
event.preventDefault();
var data = {
action: "studien_search",
type: $("#taxonomy-market-type").val(),
};
var html;
$.ajax({
url: ajaxurl,
data: data,
success: function (response) {
if(response)
{
// probably here I need to send filtered data back to PHP file and write them again
}
}
});
})
});
我使用自定义简码和回调()函数:
function search_callback()
{
header('Content-Type: application/json;charset=utf-8');
$type = "";
$type = $_GET['type'];
$args = array(
"post_type" => "studien",
"post_per_page" => -1,
"relation" => "AND"
);
if($type != "") {
$args['tax_query'][] = array(
'taxonomy' => 'market',
'field' => 'slug',
'terms' => $type
);
$search_query = new WP_Query($args);
// echo json_encode($search_query);
}
else{
$search_query = new WP_Query( $args );
}
if ( $search_query->have_posts() ) {
$result = array();
while ($search_query->have_posts()) {
$search_query->the_post();
$result[] = array(
"id" => get_the_ID(),
"title" => get_the_title(),
"permalink" => get_permalink(),
);
};
wp_reset_query();
echo json_encode($search_query);
}
else {
// nothing
}
wp_die(); global $argsAjaxFilter;
$argsAjaxFilter = $search_query;
}
如您所见,$search_query 代表我过滤后的数据。这是根据教程的方法,但我不能使用响应数组()......对我来说最好的方法是以某种方式将 $search_query 发送到 PHP 文件,在那里我可以再次编写新的自定义帖子类型数据。拜托,有人给我建议吗?这是个好建议吗?
【问题讨论】:
-
当你应该返回
$result时,你却返回了$search_query -
是的,但是我需要在 ajax 函数中处理结果,并且某些 php 变量无法在 javascript 字符串中回复。这就是我需要以某种方式将新的 $search_query 发送到我的 php 文件的原因...不喜欢在 ajax 响应中创建 html 字符串。另外我希望作为响应存在某种方式如何将 $search_query 发送回 PHP 文件并再次执行 while 循环,但使用过滤数据
-
我认为您需要更具体一些。您想在 php 或 js 中呈现 html 响应吗?搜索细化究竟涉及什么?
-
是的,我想在 php 中呈现响应,而不是在 JS 中。javascript 无法处理一些 php 变量。这是我的问题的重点,在我的示例中,我在 JS 中有响应,但我必须更改对 PHP 的响应
-
"javascript 无法处理一些 php 变量" 在通常的设置中,Javascript 无法处理 any PHP 变量;它在客户端运行,而 PHP 在服务器上处理。有像
node.js这样的服务器端Javascript,但我们显然不是在这里谈论这个。我想你一般对 AJAX、PHP 和 JS 感到困惑。
标签: javascript php ajax wordpress