Multiple Tags Issue in Permalinks

There is a column in the term_relationships table for term_order which seems to imply that one could set the order of terms. That said, it looks like it doesn’t actually work — the core doesn’t use it in any way.

A bit of poking around in wp_set_object_terms, the function that get’s used to assign terms to objects (post types, users) revealed this little gem:

<?php
$t = get_taxonomy($taxonomy);
if ( ! $append && isset($t->sort) && $t->sort ) {
    $values = array();
    $term_order = 0;
    $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids'));
    foreach ( $tt_ids as $tt_id )
        if ( in_array($tt_id, $final_tt_ids) )
            $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order);
    if ( $values )
        if ( false === $wpdb->query( "INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join( ',', $values ) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)" ) )
            return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error );
}

Which makes it appear that one could set the sort argument on taxonomies to true and WP will sort things for you. The sort argument seems undocumented, but a bit of test code reveals that it does indeed work.

<?php
add_action('init', 'wpse72703_modify_tags', 100);
function wpse72703_modify_tags()
{
    global $wp_taxonomies;
    $wp_taxonomies['post_tag']->sort = true;
}

The only thing you’ll need to do differently in the using tags in permalinks is to change this:

$tags = get_the_tags( $post->ID );

to…

$terms = wp_get_object_terms($post->ID, 'post_tag', array(
    'orderby' => 'term_order',
));

Which will force the returned terms to respect the order in which you added them.