How to use first tag in permalinks

Use add_rewrite_tag() to register the placeholder, and filter post_link to insert the correct tag. Use get_the_tags() to get the tags for a post.

Sample plugin I have used in a project:

<?php
/**
 * Plugin Name: T5 Tag as rewrite tag
 * Description: Use <code>%tag%</code> in permalinks.
 * Version:     2012.09.02
 * Author:      Thomas Scholz
 * Author URI:  http://toscho.de
 * Licence:     MIT
 * License URI: http://opensource.org/licenses/MIT
 */

add_action( 'init', array ( 'T5_Rewrite_Tag_Tag', 'init' ) );

/**
 * Adds '%tag%' as rewrite tag (placeholder) for permalinks.
 */
class T5_Rewrite_Tag_Tag
{
    /**
     * Add tag and register 'post_link' filter.
     *
     * @wp-hook init
     * @return  void
     */
    public static function init()
    {
        add_rewrite_tag( '%tag%', '([^/]+)' );
        add_filter( 'post_link', array( __CLASS__, 'filter_post_link' ) , 10, 2 );
    }

    /**
     * Parse post link and replace the placeholder.
     *
     * @wp-hook post_link
     * @param   string $link
     * @param   object $post
     * @return  string
     */
    public static function filter_post_link( $link, $post )
    {
        static $cache = array (); // Don't repeat yourself.

        if ( isset ( $cache[ $post->ID ] ) )
            return $cache[ $post->ID ];

        if ( FALSE === strpos( $link, '%tag%' ) )
        {
            $cache[ $post->ID ] = $link;
            return $link;
        }

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

        if ( ! $tags )
        {
            $cache[ $post->ID ] = str_replace( '%tag%', 'tag', $link );
            return $cache[ $post->ID ];
        }

        $first              = current( (array) $tags );
        $cache[ $post->ID ] = str_replace( '%tag%', $first->slug, $link );

        return $cache[ $post->ID ];
    }
}

Leave a Comment