I have configured %tag% for permalinks in wordpress Here is How to use first tag in permalinks. But while posting multiple tags in a post i am facing a kind of problem.
Suppose i have wrote three tags for a post, they are: Backlinks, All About SEO, Web Promotion
So here i wanna use the first tag name only in permalinks, but the problem is all tags are sorted by character in a post, so unfortunately in permalink it will use www.example.com/All About SEO/page/ though i want to use the first tag in permalinks,so in this case desired permalink should be like this: www.example.com/Backlinks/page/
So, how to use the first tag name for the permalinks please help :)


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:

$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.

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


$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.

| improve this answer | |
  • 1
    Great solution, thanks. I have added it to my plugin now. See download. – fuxia Nov 16 '12 at 1:58
  • Awesome! I was actually planning on sending you a pull request about that later tonight. – chrisguitarguy Nov 16 '12 at 2:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.