在WordPress 3.1中使用新的“POSTS_子句”筛选器?

时间:2011-05-13 作者:Manny Fleurmond

刚刚注意到3.1添加了一个新的过滤器来定制查询:posts\\u子句。我所能找到的只是,不用使用单独的查询过滤器,如posts\\u where或posts\\u join,您可以一次性编辑它们。我想知道是否有人可以举例说明新的“posts\\u子句”过滤器的用法?

2 个回复
最合适的回答,由SO网友:Hameedullah Khan 整理而成

下面是我在某处找到并正在进行的查询。查询的目的是根据分类法对帖子进行排序。因此,我正在共享代码,以便它可以帮助您理解posts\\u子句的用法。

function color_clauses_mike( $clauses, $query ) {
global $wpdb;

if ( isset( $query->query[\'orderby\'] ) && \'color\' == $query->query[\'orderby\'] ) {

    $clauses[\'join\'] .= <<<SQL
LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id)
LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
SQL;

    $clauses[\'where\'] .= " AND (taxonomy = \'color\' OR taxonomy IS NULL)";
    $clauses[\'groupby\'] = "object_id";
    $clauses[\'orderby\']  = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
    $clauses[\'orderby\'] .= ( \'ASC\' == strtoupper( $query->get(\'order\') ) ) ? \'ASC\' : \'DESC\';
}

return $clauses;
}
add_filter( \'posts_clauses\', \'color_clauses_mike\', 10, 2 );
以下是我找到上述查询的来源:http://scribu.net/wordpress/sortable-taxonomy-columns.html

SO网友:Yousef

scribu/Hameedullah的答案是一个很好的指针,但它会隐藏属于不同分类法(例如“类别”)的帖子,而不是“颜色”的帖子。我修改了代码,这似乎很有效:

if ( isset( $wp_query->query[\'orderby\'] ) && \'color\' == $wp_query->query[\'orderby\'] ) {

    $clauses[\'join\'] .= <<<SQL
LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} ON wp_term_taxonomy.term_taxonomy_id=wp_term_relationships.term_taxonomy_id AND wp_term_taxonomy.taxonomy=\'color\'
LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
SQL;

    $clauses[\'groupby\'] = "wp_posts.ID";
    $clauses[\'orderby\']  = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
    $clauses[\'orderby\'] .= ( \'ASC\' == strtoupper( $wp_query->get(\'order\') ) ) ? \'ASC\' : \'DESC\';
}

结束