我终于在Wordpress中实现了实时搜索,但只有在课堂上直接调用它时,它才起作用。
我想把它放在一个短代码中,这样我就可以在我想要的每一页上调用它。但是,当我调用短代码时,我的jquery/ajax不起作用。
Constructor
add_action( \'wp_ajax_schoenen_zoeken_shortcode_output\', array($this, \'schoenen_zoeken_shortcode_output\'));
add_action( \'wp_ajax_nopriv_schoenen_zoeken_shortcode_output\', array($this, \'schoenen_zoeken_shortcode_output\'));
add_action( \'wp_head\', array($this, \'add_js\' ));
add_action( \'init\', array($this, \'register_schoenen_shortcodes\'));
Javascript:
public function add_js() {
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$(\'#searchid\').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
<?php
}
Shortcode
public function register_schoenen_shortcodes() {
add_shortcode(\'schoenen_zoeken\', array($this, \'schoenen_zoeken_shortcode_output\'));
}
PHP AND HTML
public function schoenen_zoeken_shortcode_output() {
global $wpdb;
if ($_POST) {
$q = mysql_real_escape_string($_POST[\'search\']);
foreach ($wpdb->get_results("SELECT plaatsen FROM wp_plaatsen WHERE plaatsen LIKE \'%$q%\'") as $key => $row) {
$plaatsnaam = $row->plaatsen;
$b_plaatsnaam = \'<strong>\'.$q.\'</strong>\';
$final_plaatsnaam = str_ireplace($q, $b_plaatsnaam, $plaatsnaam);
?>
<div class="show" align="left">
<span class="name"><?php echo $final_plaatsnaam; ?></span>
</div>
<?php
}
die();
}
?>
<div class="schoen_zoeken_container">
<div class="schoen_zoeken">
<form action="" method="POST">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="zoeken">
<input type="text" class="search" id="searchid" name="search" placeholder="Zoek schoen" />
<div id="result">
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<?php
}