Wordpress WP_查询筛选自定义分类法或自定义post_类型中的关键字搜索
我想知道它是否可以按文章标题或自定义分类进行过滤 例如:我搜索“人类”,我想显示在文章标题和类别“人类”中包含“人类”一词的文章 -如果“人类”类别不存在且存在标题为“人类”的帖子,则不排除帖子Wordpress WP_查询筛选自定义分类法或自定义post_类型中的关键字搜索,wordpress,Wordpress,我想知道它是否可以按文章标题或自定义分类进行过滤 例如:我搜索“人类”,我想显示在文章标题和类别“人类”中包含“人类”一词的文章 -如果“人类”类别不存在且存在标题为“人类”的帖子,则不排除帖子 -如果存在“人类”类别,并且存在标题为“人类”的帖子,则不排除帖子(检索包含“人类”一词的所有帖子以及包含“人类”类别的所有帖子)我认为应该尝试使用此过滤器posts\u其中 方法1: $args = array( 'post_title_like' => $str ); $res = n
-如果存在“人类”类别,并且存在标题为“人类”的帖子,则不排除帖子(检索包含“人类”一词的所有帖子以及包含“人类”类别的所有帖子)我认为应该尝试使用此过滤器
posts\u其中
方法1:
$args = array(
'post_title_like' => $str
);
$res = new WP_Query($args);
$mypostids = $wpdb->get_col("select ID from $wpdb->posts where post_title LIKE '".$str."%' ");
$args = array(
'post__in'=> $mypostids,
'post_type'=>'post',
'orderby'=>'title',
'order'=>'asc'
);
$res = new WP_Query($args);
while( $res->have_posts() ) : $res->the_post();
// put your logic here
endwhile;
在functions.php文件中
<?php
add_filter( 'posts_where', 'title_like_posts_where', 10, 2 );
function title_like_posts_where( $where, &$wp_query ) {
global $wpdb;
if ( $post_title_like = $wp_query->get( 'post_title_like' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $post_title_like ) ) . '%\'';
}
return $where;
}
?>
方法2:
$args = array(
'post_title_like' => $str
);
$res = new WP_Query($args);
$mypostids = $wpdb->get_col("select ID from $wpdb->posts where post_title LIKE '".$str."%' ");
$args = array(
'post__in'=> $mypostids,
'post_type'=>'post',
'orderby'=>'title',
'order'=>'asc'
);
$res = new WP_Query($args);
while( $res->have_posts() ) : $res->the_post();
// put your logic here
endwhile;
我不确定你是否找到了解决这个问题的方法,但我认为古弗兰的答案并不完全是解决这个问题的方法 我还需要在标题、内容、摘录或类别名称中进行搜索,但遇到了一个问题,因为查询排除了类别之外的点击。我的解决方案是进行两次查询并合并结果
//search within title of category
$args1 = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 500,
'orderby' => 'title',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'title',
'terms' => 'human',
)
)
);
//search within title/excerpt/content
$args2 = array(
's' => 'human',
'post_type' => 'businesses',
'post_status' => 'publish',
'posts_per_page' => 500,
'orderby' => 'title',
'order' => 'ASC'
);
$query1 = new WP_Query($args1);
$query2 = new WP_Query($args2);
$loop = new WP_Query();
$loop->posts = array_merge( $query1->posts, $query2->posts );
//populate post_count count for the loop to work correctly
$loop->post_count = $query1->post_count + $query2->post_count;
嗨,你找到解决办法了吗?我也在同一条船上。