wordpress - Wordpress,也搜索帖子的类别描述(或 term_taxonomy.description LIKE %A%)
问题描述
我正在努力寻找一种简单的 wordpress 搜索方法来搜索帖子的类别描述。我发现很少的主题,但没有真正的答案。
问题是,用户可能也在输入他们搜索的内容 + 类别名称(例如,“Mario Nintendo 64”,其中“Nintendo 64”是类别名称。截至目前,它不会返回任何结果,这感觉不对)。
我需要在 term_taxonomy.description 中搜索,因为类别有别名,我在此字段中输入(例如:“Nintendo 64, N64 etc...”)
这是我想出的。
function custom_posts_join ($a) {
global $wpdb;
return $a . " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_id) ";
}
function custom_posts_where ($a) {
global $wpdb;
return $a . " AND $wpdb->term_taxonomy.taxonomy = 'category'";
}
add_filter('posts_join', custom_posts_join );
add_filter('posts_where', custom_posts_where );
尽管如此,我现在需要能够集成OR (term_taxonomy.description LIKE '%A%')
到搜索中,sql请求只搜索
(posts.post_title LIKE '%A%')
OR (posts.post_excerpt LIKE '%A%')
OR (posts.post_content LIKE '%A%')
此外,基于帖子可以属于多个类别的事实,是否可以添加 DISTINCT,因此它不会多次返回同一个帖子。
我真的不知道我是否在正确的道路上,但我被困住了。另外我想知道有多重,可能看起来有点调整,结果会在服务器上?多年来我一直没有开发,现在我又回到了它,我不确定这是否会使搜索变得过于繁重。INNER JOIN 是最好的方法吗?
是否有另一种方法可以处理搜索以在帖子的类别描述中进行搜索。
解决方案
经过数小时的研究,我终于取得了进展,一切正常!
这是现在的样子:
function custom_posts_join ( $join ) {
global $wpdb;
if ( is_search() ) {
$join .= " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_id) ";
}
return $join;
}
function custom_posts_where ( $where ) {
global $wpdb;
if ( is_search() ) {
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->term_taxonomy.".description LIKE $1)", $a );
$where .= " AND $wpdb->term_taxonomy.taxonomy='category'";
}
return $where;
}
add_filter('posts_join', custom_posts_join );
add_filter('posts_where', custom_posts_where );
并添加 DISTINCT:
function custom_posts_distinct ( $distinct ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT";
}
return $distinct;
}
add_filter( 'posts_distinct', 'custom_posts_distinct' );
不过,性能如何,每次研究都做 2 INNER JOIN?
无论如何,这是一个完整的解决方案,我希望这会对某人有所帮助。
推荐阅读
- windows - EC2实例启动后如何创建AWS Windows EC2并设置2个网页打开?
- android - 应用程序关闭时工作管理器不工作?
- php - JQuery/Ajax html 只加载一次
- python - 如何将数据帧中的多个元组列表组合到一个字典中?
- android - 如果应用程序从最近的菜单中被杀死,如何强制停止任何插件
- java - java.sql.SQLException:字段“participant_one_fk_id”没有默认值
- javascript - React :: 上下滚动时部分变白
- reactjs - React-card-flip,通过数据映射并一次翻转一张卡片
- redis - Redisson 将 ArrayList 或 RList 放入 RMap 中。会发生什么?
- python - 围绕枢轴 Python 绘制旋转图像