是否按帖子日期顺序检索分类术语?

时间:2014-06-03 作者:Jonathan Christopher

我正在构建一个自定义分类法归档页面,该页面需要按相关帖子的顺序列出术语post_date. 我写了这篇文章,它很有效,但我讨厌求助于自定义SQL:

global $wpdb;

$post_types = array( \'series\' );
$taxonomy   = array( \'taxonomy\' );
$order      = \'DESC\';

$sql = "SELECT DISTINCT t.*
    FROM $wpdb->terms AS t
    INNER JOIN $wpdb->term_taxonomy AS tt
        ON t.term_id = tt.term_id
    JOIN $wpdb->term_relationships AS tr
        ON tr.term_taxonomy_id = tt.term_taxonomy_id
    JOIN $wpdb->posts AS p
        ON p.ID = tr.object_id
    WHERE tt.taxonomy IN ( \'" . implode( "\',\'", $taxonomy ) . "\' )
    AND p.post_type IN ( \'" . implode( "\',\'", $post_types ) . "\' )
    ORDER BY p.post_date {$order};";

$terms_ordered_by_post_date = $wpdb->get_results( $sql );
好奇是否有人有更好的解决方案?

1 个回复
最合适的回答,由SO网友:SergeyBiryukov 整理而成

我会使用terms_clauses 过滤,然后使用get_terms():

function wpse147412_order_terms_by_post_date( $pieces, $taxonomies, $args ) {
    global $wpdb;

    if ( \'post_date\' !== $args[\'orderby\'] ) {
        return $pieces;
    }

    $args = wp_parse_args( $args, array( \'post_types\' => \'post\' ) );

    $pieces[\'fields\']   = \'DISTINCT \' . $pieces[\'fields\'];
    $pieces[\'join\']    .= " JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id";
    $pieces[\'join\']    .= " JOIN $wpdb->posts AS p ON p.ID = tr.object_id";
    $pieces[\'where\']   .= " AND p.post_type IN (\'" . implode( "\', \'", (array) $args[\'post_types\'] ) . "\')";
    $pieces[\'orderby\']  = \'ORDER BY p.post_date\';

    return $pieces;
}
add_filter( \'terms_clauses\', \'wpse147412_order_terms_by_post_date\', 10, 3 );

....

$terms = get_terms( \'taxonomy\', array( \'post_types\' => \'series\', \'orderby\' => \'post_date\', \'order\' => \'DESC\' ) );

结束