要在Typecho中添加实时搜索功能,可以通过以下步骤实现:首先,在Typecho的主题中添加一个搜索框,可以在主题的header.php文件中添加以下代码:options>siteUrl();...
要在Typecho中添加实时搜索功能,可以通过以下步骤实现:
首先,在Typecho的主题中添加一个搜索框,可以在主题的header.php文件中添加以下代码:
<form method="get" id="searchform" action="<?php $this->options->siteUrl(); ?>">
<input type="text" name="s" class="text" placeholder="Search..." />
<button type="submit" class="submit">Search</button>
</form>
然后,在Typecho的functions.php文件中添加以下代码,用于处理搜索请求:
function real_time_search($keywords) {
$db = Typecho_Db::get();
$keywords = $db->escape($keywords);
$sql = $db->select()->from('table.contents')
->where('type = ?', 'post')
->where('status = ?', 'publish')
->where('title LIKE ?', '%' . $keywords . '%')
->order('created', Typecho_Db::SORT_DESC)
->limit(10);
$result = $db->fetchAll($sql);
$data = array();
foreach ($result as $post) {
$data[] = array(
'title' => $post['title'],
'permalink' => $post['permalink']
);
}
echo json_encode($data);
die();
}
接着,在Typecho的header.php文件中添加以下JavaScript代码,用于实现实时搜索功能:
$(document).ready(function() {
$('#searchform input[type="text"]').on('input', function() {
var keywords = $(this).val();
$.ajax({
url: '<?php $this->options->index('/search'); ?>',
type: 'POST',
data: { keywords: keywords },
success: function(data) {
var results = JSON.parse(data);
// 清空搜索结果
$('#search-results').empty();
// 显示搜索结果
results.forEach(function(result) {
$('#search-results').append('<a href="' + result.permalink + '">' + result.title + '</a>');
});
}
});
});
});
最后,在Typecho的functions.php文件中添加以下代码,用于处理搜索请求:
if ($request->isPost() && $request->pathinfo == '/search') {
$keywords = $request->get('keywords');
real_time_search($keywords);
}
通过以上步骤,您就可以在Typecho中实现实时搜索功能了。用户在搜索框中输入关键词时,会实时显示相关的搜索结果。