我是一名初学者前端开发人员,这是我使用Wordpress的第一步。
如何显示标题或内容中包含来自搜索输入的搜索词的帖子?我不想在其重新加载页面上使用插件或内置的Wordpress搜索。
这是我的代码:
HTML
<form class="search__form" action="" method="POST">
<div class="search__input-container">
<input type="text" name="search" class="search__input search__input-js" placeholder="Search">
</div>
</form>
JavaScript
$('.search__input-js').on('change', function(){
var search = $('.search__input').val();
search = search.toLowerCase();
$.ajax({
type: 'POST',
url: ajax_options.admin_ajax_url,
data:{
search: search,
action: 'ajax_func'
},
success: function(result) {
$('.return-msg').html('');
$('.return-msg').html(result);
},
error: function(e) {
console.log(e);
}
});
});
Functions.php
function ajax_func() {
wp_reset_postdata();
$search_term = '';
$result = '';
if(isset($_POST['search'])){
$search_term .= $_POST['search'];
}else{
$search_term = '';
}
$args= array(
'post_type' => array('post', 'case-study'),
'HERE'
);
$the_query_posts = new WP_Query( $args );
if ( $the_query_posts->have_posts() ) {
while ( $the_query_posts->have_posts() ) {
$the_query_posts->the_post();
$result .='
<div class="col-lg-4">';
$result .='
<a class="post__link" href="'.get_the_permalink().'">
<div class="post__container">';
if (has_post_thumbnail()) {
$result .= '
'.get_the_post_thumbnail(get_the_ID(), 'post-thumbnail', ['class' => 'post__img', 'alt' => get_the_title()]).'
';
} else {
$result .= '
<img class="img-responsive responsive--full post__img" src="" />
';
}
$result .='
<div class="post__background">
<p class="post__category">'.get_the_category(get_the_ID())[0]->name .'</p>';
$result .='<p class="post__name">'.get_the_title().'</p>';
$result .='<div class="post__desc">'.get_field('post_short_desc').'</div>';
$result .='
</div>
</div>
</a>
</div>';
}
wp_reset_postdata();
} else {
$result .= '<div class="col-12">0 posts</div>';
wp_reset_postdata();
}
echo $result;
die();
}
remove_filter( 'posts_where', 'cc_post_title_filter', 10, 2 );
add_action('wp_ajax_nopriv_ajax_func', 'ajax_func');
add_action('wp_ajax_ajax_func', 'ajax_func');
Ajax可以正常工作,我知道我应该编写一些函数并设置一个特殊的WP查询来查找我写“ HERE”的帖子,但是我不知道如何写。有人可以给我一个提示吗?
答案 0 :(得分:0)
WP_Query has a search parameter您可以传递给它。如果您不想使用AJAX,它也是内置的(example.com/?s=query+here)。总共看起来像这样:
user