web-dev-qa-db-fra.com

Récupérer les termes de taxonomie dans l'ordre de la date de leur message?

Je crée une page d'archive de taxonomie personnalisée qui doit répertorier les termes dans l'ordre correspondant à la publication post_date de leur publication associée. J'ai écrit ceci, ça marche, mais je déteste avoir recours à du SQL personnalisé:

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 );

Curieux si quelqu'un a une meilleure solution?

1

Je voudrais utiliser le filtre terms_clauses , puis simplement utiliser 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' ) );
1
SergeyBiryukov