首先要做的是检查是否有影响搜索结果的插件。原因是我运行了“搜索一切”插件。虽然它旨在搜索更多结果并突出显示搜索词,但它将更改new WP_Query();
使其无用。
这是用ajax加载帖子的回调函数。调用函数的工作方式与任何其他客户端请求类似,将结果回显到空div。
function cbSearch()
{
$counter = 1;
$max = 4;
$html = "";
//Variables passed through $_POST
$s = $_POST[\'src\'];
//the first time you call this function page number should be 1
//Additional pages/functions/links are created with this code
$page_num = $_POST[\'idx\'];
//Assuming the old $wp_query is basically null,
//there\'s no reason to copy previous parameters, just make a new one
$search_query = array(\'s\' => $s, \'posts_per_page\' => $max, \'paged\' => $page_num, \'post_type\' => \'post\', \'post_status\' => \'publish\');
$search = new WP_Query($search_query);
//use the object created, have_posts() alone will use global $wp_query
if ($search->have_posts())
{
//The variables required to figure out next or previous page
//Total number of post that match $s
$total = $search->found_posts;
//Post count for the page you\'re on
$post_count = $search->post_count;
//The maximum amount of pages to display all of the post results
$page_count = ceil($search->max_num_pages);
while ($search->have_posts())
{
//Setup post data !important
$search->the_post();
//Now your in the loop, use any loop functions you want
$title = highlight(get_the_title(), $s);
}
$html = "<div id=\'news-page-nav\'>";
//Since we know what page we\'re on we know where to go
$pre = $page_num - 1;
$nex = $page_num + 1;
if ($pre > 0)
{
$html .= "<span class=\'left fg-grey-light pointer\' onclick=\'searchPosts(" . $pre . ");return false;\' >P</span>";
}
if ($nex <= $page_count)
{
$html .= "<span class=\'right fg-grey-light pointer\' onclick=\'searchPosts(" . $nex . ");return false;\' >N</span>";
}
$html .= "</div>";
echo $html;
}
else
{
echo false;
}
die();
}
function highlight($str, $mts)
{
$keys = explode(" ", $mts);
$title = preg_replace(\'/(\' . implode(\'|\', $keys) . \')/iu\', \'<span class="bg-highlight">\\0</span>\', $str);
return $title;
}
不可能将上一篇/下一篇文章的链接与ajax一起使用,因为提供的链接是加载新页面的URL。我不得不提醒自己,使用AJAX时,页面不会重新加载以提供新内容。我创建了两个“链接”,它们再次调用ajax函数,但页码不同。现在,您可以在不使用WP的默认url参数的情况下分页搜索结果。需要记住的是,这将如何影响搜索引擎结果。