在WordPress Permalinks中添加自定义分类标记,您希望做的是在Permalink结构中使用您的分类,例如:。/%actor%/%postname%
首先,您要像之前一样编写分类法,但需要额外的字段:
add_action(\'init\', \'add_actor_taxonomy\');
function add_actor_taxonomy() {
if (!is_taxonomy(\'actor\')) {
register_taxonomy( \'actor\', \'post\',
array(
\'hierarchical\' => FALSE,
\'label\' => __(\'actor\'),
\'public\' => TRUE,
\'show_ui\' => TRUE,
\'query_var\' => \'actor\',
\'rewrite\' => true, // this adds the tag %actor% to WordPress
)
);
}
}
即使已将%actor%标记添加到WordPress中,在您告诉WordPress如何翻译该标记之前,它也不会起作用。
// The post_link hook allows us to translate tags for regular post objects
add_filter(\'post_link\', \'actor_permalink\', 10, 3);
// The post_type_link hook allows us to translate tags for custom post type objects
add_filter(\'post_type_link\', \'actor_permalink\', 10, 3);
function actor_permalink($permalink, $post_id, $leavename) {
// If the permalink does not contain the %actor% tag, then we don’t need to translate anything.
if (strpos($permalink, \'%actor%\') === FALSE) return $permalink;
// Get post
$post = get_post($post_id);
if (!$post) return $permalink;
// Get the actor terms related to the current post object.
$terms = wp_get_object_terms($post->ID, \'actor\');
// Retrieve the slug value of the first actor custom taxonomy object linked to the current post.
if ( !is_wp_error($terms) && !empty($terms) && is_object($terms[0]) )
$taxonomy_slug = $terms[0]->slug;
// If no actor terms are retrieved, then replace our actor tag with the value "actor"
else
$taxonomy_slug = \'actor\';
// Replace the %actor% tag with our custom taxonomy slug
return str_replace(\'%actor%\', $taxonomy_slug, $permalink);
}
使用如下自定义permalink结构
/%actor%/%postname%
您的新帖子链接如下所示
http://website.com/james-franco/127-hours
参考号:
http://shibashake.com/wordpress-theme/add-custom-taxonomy-tags-to-your-wordpress-permalinks