使用add_rewrite_tag()
注册占位符并筛选post_link
插入正确的标记。使用get_the_tags()
获取帖子的标签。
我在项目中使用的插件示例:
<?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 ];
}
}