在过去的几个小时里,我一直在尝试使用过滤器挂钩posts_where
和posts_join
要根据分类法术语搜索帖子,在本例中,分类法为“category”,术语为“politics”
这是我尝试的结果,结果是一个空查询:
这条线在钩子里posts_where
$where .= " OR ($wpdb->term_taxonomy.taxonomy IN (\'category\') AND $wpdb->terms.name = \'politics\')";
这就是我用来连接不同表的方法:
$join .= " LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";
$join .= " LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) ";
$join .= " LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";
$join .= " LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id) ";
我确实想出了一个可行的替代方案,但我想知道我在前面的代码中犯了什么错误,以及如何使其工作。
可行的替代方案是这样的(不使用posts_join
挂钩):
$search .= " OR ($wpdb->posts.ID IN(
SELECT $wpdb->term_relationships.object_id as post_id
FROM $wpdb->term_taxonomy, $wpdb->terms, $wpdb->term_relationships
WHERE $wpdb->term_taxonomy.term_id = $wpdb->terms.term_id
AND $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id
AND $wpdb->term_taxonomy.taxonomy in (\'category\')
AND ($wpdb->terms.name LIKE \'politics\')
)
)";
那么,我如何使用
posts_where
和
posts_join
查询分类术语的挂钩?
SO网友:Gixty
嗯,在尝试了不同的事情之后,我想到了以下几点。
当我们使用posts_join
无需添加前缀$wpdb->
加上要查询的表。我们只需要列名。在这种情况下,我们只需要name
和taxonomy
, 像这样:
BEFORE
$where .= " OR ($wpdb->term_taxonomy.taxonomy IN (\'category\') AND $wpdb->terms.name LIKE \'politics\')";
AFTER
$where .= " OR ( taxonomy IN (\'category\') AND name LIKE \'politics\')";
最好指出,随着查询变得越来越复杂,应该使用别名。
使用别名如下所示:
For posts_where
hook:
$where .= " OR (wtt.taxonomy IN (\'category\') AND wt.name LIKE \'politics\' )";
For posts_join
hook:
$join .= " LEFT JOIN $wpdb->term_relationships as wtr ON ($wpdb->posts.ID = wtr.object_id) ";
$join .= " LEFT JOIN $wpdb->term_taxonomy as wtt ON (wtr.term_taxonomy_id = wtt.term_taxonomy_id) ";
$join .= " LEFT JOIN $wpdb->terms as wt ON(wtt.term_id = wt.term_id) ";