使用AJAX加载Wordpress搜索结果 [英] Load Wordpress search results using AJAX
问题描述
我正在尝试使用AJAX在同一页面上加载我的WordPress搜索结果。但我无法弄清楚如何在页面上显示搜索结果。
I'm trying to load my WordPress search results on the same page using AJAX. But I can't figure out how to show the search results on the page.
我用谷歌搜索并找到了很多代码,但大部分代码都不适用于我。我最接近的就是这个。这是我到目前为止所做的。
I googled and found a lot of code but most of them didn't work for me. The closest I'm getting is with this. Here is what I've got so far.
HTML
<section id="toplevel-frontpage">
<div class="container">
<div class="block">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-8 col-lg-8">
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
Search:<input type="text" name="str" id="str">
<input type="submit" value="send" id="send">
</form>
<div id="search_results"></div>
</div>
</div>
</div>
</div>
</section>
jQuery (阻止搜索转到其他页面并加载AJAX文件)
jQuery (to stop the search from going to an other page and load the AJAX file)
$(function() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
$.post('wp-content/themes/MyTheme/includes/search-post-results.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
search-post-results.php
这就是我被困住的地方。如果我加载正常的循环
我得到500内部服务器错误。现在我得到了这个:
This is where I'm stuck. If I load a normal loop
I get 500 Internal server error. Right now I got this:
<?php session_start(); ?>
<?php
/*
Template Name: Search Page
*/
?>
<?php
$value = $_POST['value'];
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
echo sprintf( __( '%s Search Results for ', 'html5blank' ), $wp_query->found_posts ); echo get_search_query();
?>
我认为我必须包含WordPress核心文件,所以我可以使用WordPress代码,但 echo get_search_query()
什么都不做? $ _ POST ['value'];
输出搜索输入。
I figured I had to include the WordPress Core files so I could use WordPress code, but echo get_search_query()
does nothing? $_POST['value'];
outputs the input of the search.
推荐答案
您的代码有效。我把它写成了一个插件。我可以不在没有你的代码的情况下加载AJAX。我唯一改变的是评论以下因为它与其他插件冲突并且抛出错误,但没有它就可以很好地工作(需要加载wp-config.php)。
Your code works. I wrote this into a plugin. I could not get AJAX to load without your code. The only thing I changed was commenting out the following because it conflicted with other plugins and was throwing errors, but it works beautifully without it (loading wp-config.php was required).
// include_once $path . '/wp-load.php';
// include_once $path . '/wp-includes/wp-db.php';
// include_once $path . '/wp-includes/pluggable.php';
非常感谢您为我们更新您的工作代码。
Thank you so much for updating your working code for us.
这篇关于使用AJAX加载Wordpress搜索结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!