我无意中发现了这一点,我在寻找一种解决方案,从WP_Query
根据他们的相关术语,这似乎是这个问题的精髓。(我将回答一般说明下面问题的特殊搜索案例。)
按相关术语对帖子进行排序,所以关键是MySQL函数FIELD()
只需将一个过滤器连接到posts_orderby
结合使用tax_query
.
使用tax_query
的参数WP_Query
必须»加入«wp_posts
具有的表格wp_term_relationships
谁的列term_taxonomy_id
我们想订购。
如果不想排队等待特定条款,只需将所有条款作为值传递:
# get all terms of \'category\' ordered by the terms name (default behaviour)
$terms = get_terms( \'category\', array( \'fields\' => \'ids\' ) );
$query_args = array(
\'tax_query\' => array(
array(
\'taxonomy\' => \'category\',
\'field\' => \'id\',
\'terms\' => $terms
)
)
);
/**
* the filter callback
* removes itself from the applied filter
*
* @wp-hook posts_orderby
* @param string $sql (Default oderby clause)
* @param WP_Query $query
* @uses $terms which are allready in the correct order
* @return string
*/
$orderby_terms = function( $sql, $query ) use ( $terms, &$orderby_terms ) {
$field = $GLOBALS[ \'wpdb\' ]->term_relationships . \'.term_taxonomy_id\';
$terms = array_map( \'intval\', $terms );
$sql = sprintf(
\'FIELD( %1$s, %2$s ) \',
$field,
implode( \', \', $terms )
);
remove_filter( current_filter(), $orderby_terms );
return $sql;
};
add_filter( \'posts_orderby\', $orderby_terms, 10, 2 );
$query = new \\WP_Query( $query_args );
更详细地回答问题:因为您需要
tax_query
参数
限制此查询不会获取未分配给任何术语的帖子。这与其他分类法有关category
.如果一篇文章被分配到多个术语,排序可能不像您预期的那样容易理解,因为对于每一篇文章,只考虑一个术语关系(SQL中的GROUP By子句)特殊情况:搜索查询上述方法可应用于默认搜索查询,如下所示:您可以pre_get_posts
并确保它是主要的搜索查询。
function wpse_91993_order_search( $query ) {
if ( ! $query->is_main_query() && ! $query->is_search() )
return;
$terms = get_terms( \'category\', array( \'fields\' => \'ids\' ) );
$tax_query_args = array(
array(
\'taxonomy\' => \'category\',
\'field\' => \'id\',
\'terms\' => $terms
)
);
$query->set( \'tax_query\', $tax_query_args );
/**
* the filte callback
* removes itself from the applied filter
*
* @wp-hook posts_orderby
* @param string $sql (Default oderby clause)
* @param WP_Query $query
* @uses $terms which are allready in the correct order
* @return string
*/
$orderby_terms = function( $sql, $query ) use ( $terms, &$orderby_terms ) {
$field = $GLOBALS[ \'wpdb\' ]->term_relationships . \'.term_taxonomy_id\';
$terms = array_map( \'intval\', $terms );
$sql = sprintf(
\'FIELD( %1$s, %2$s ) \',
$field,
implode( \', \', $terms )
);
remove_filter( current_filter(), $orderby_terms );
return $sql;
};
add_filter( \'posts_orderby\', $orderby_terms, 10, 2 );
}
add_action( \'pre_get_posts\', __NAMESPACE__ . \'\\wpse_91993_order_search\' );
But that will ignore pages and attachments which are considered by default in the WordPress search query. 通常甚至没有为分类法注册
category
. 此时,正确的解决方案取决于您需要做出的一些决定:
是否可以注册分类法category
至岗位类型page
和attachment
并确保这些帖子至少链接到默认术语将搜索分为两个查询,一个用于如上所示的帖子,另一个用于页面和附件,并在主题中分别显示结果更改SQL请求以合并页面和附件上的选择和按条款排序的帖子上的选择是否值得?(我甚至不确定这是否可能)