我尝试使用ajax在wordpress中配置搜索区域,所以我将此代码添加到函数中。php
<?php
// the ajax function
add_action(\'wp_ajax_data_fetch\' , \'data_fetch\');
add_action(\'wp_ajax_nopriv_data_fetch\',\'data_fetch\');
function data_fetch(){
$the_query = new WP_Query( array( \'posts_per_page\' => 5, \'s\' => esc_attr( $_POST[\'keyword\'] ), \'post_type\' => \'post\' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a>
<?php endwhile;
wp_reset_postdata();
else:
echo \'<h3>No Results Found</h3>\';
endif;
die();
}
// add the ajax fetch js
add_action( \'wp_footer\', \'ajax_fetch\' );
function ajax_fetch() {
?>
<script type="text/javascript">
$("input").keyup(function() {
var keyword = jQuery(\'#searchInput\').val();
if(keyword == ""){
jQuery(\'#datafetch\').html("");
} else {
jQuery.ajax({
url: \'<?php echo admin_url(\'admin-ajax.php\'); ?>\',
type: \'post\',
data: { action: \'data_fetch\', keyword: keyword },
success: function(data) {
jQuery(\'#datafetch\').html( data );
}
});
});
}
</script>
<?php
}
?>
然后在我的模板页面中,我添加了
<div class="container ">
<div class="d-flex justify-content-center ">
<div class="searchbar">
<input id="searchInput" class="search_input" type="text" name="" placeholder="Search...">
<a href="#" class="search_icon"><i class="fas fa-search"></i></a>
</div>
</div>
</div>
<div id="datafetch">
</div>
但当我填写搜索文本时,什么也没有出现,我是否遗漏了什么?谢谢你的帮助