如何修改自定义文章类型固定链接格式为ID形式
我们都知道wordpress默认是把标题作为url的,但中文标题作为url就会很丑,也不利于SEO。中文标题最好的方式就是以文字ID形式作为URL。但是自定义文章类型(custom post type)是不支持在固定连接项设置链接格式的,所以我们必须通过代码来自定义它的固定URL格式。假设我们已创建了book类型的文章,(具体怎么创建自定义文章类型不在本文讨论之列)并且用中文当做文章标题,那么默认产生的链接也将是中文,中文链接通常是编码,比较长,也很丑陋。为了让自定义文章类型的URL变的更简洁,我们就有必要通过rewrite来改写固定连接格式。
目标:将http://www.domain.com/book/harry-potter-book变成http://www.domain.com/book/88.html,也就是用文章的ID作为链接格式。要达到这个目的:创建新的rewrite规则翻译URL,添加filter(post_type_link),当get_the_permalink()函数调用时,返回正确的链接格式。
以下是两种不同的实现方式,都可以实现这个要求,代码需贴到模板文件functions.php中,并且要到后台“固定链接”设置中重新保存固定链接更新.htaccess文件后,url格式才能生效。
1、修改自定义文章类型固定链接格式方法一:
/* 重写自定义文章类型URL规则 代码来源: www.wpzxbj.com */ add_action('init', 'custom_book_rewrite'); function custom_book_rewrite() { global $wp_rewrite; $queryarg = 'post_type=book&p='; $wp_rewrite->add_rewrite_tag('%qid%', '([^/]+)', $queryarg); $wp_rewrite->add_permastruct('book', '/book/%qid%.html', false); } add_filter('post_type_link', 'custom_book_permalink', 1, 3); function custom_book_permalink($post_link, $post = 0) { global $wp_rewrite; if ( $post->post_type == 'book' ){ $post = &get_post($id); if ( is_wp_error( $post ) ) return $post; $newlink = $wp_rewrite->get_extra_permastruct('book'); $newlink = str_replace("%qid%", $post->ID, $newlink); $newlink = home_url(user_trailingslashit($newlink)); return $newlink; } else { return $post_link; } }
2、修改自定义文章类型固定链接格式方法二:
/* 重写自定义文章类型URL规则 代码来源: www.wpzxbj.com */ add_filter('post_type_link', 'custom_book_link', 1, 3); function custom_book_link( $link, $post = 0 ){ if ( $post->post_type == 'book' ){ return home_url( 'book/' . $post->ID .'.html' ); } else { return $link; } } add_action( 'init', 'custom_book_rewrites_init' ); function custom_book_rewrites_init(){ add_rewrite_rule( 'book/([0-9]+)?.html$', 'index.php?post_type=book&p=$matches[1]', 'top' ); }
3、同时修改多个custom post type自定义文章类型固定链接格式,可用以下代码实现,无需每个自定义文章类型都添加修改固定链接代码:
$mytypes = array( 'type1' => 'slug1', 'type2' => 'slug2', 'type3' => 'slug3' ); add_filter('post_type_link', 'custom_book_link', 1, 3); function custom_book_link( $link, $post = 0 ){ global $mytypes; if ( in_array( $post->post_type,array_keys($mytypes) ) ){ return home_url( $mytypes[$post->post_type].'/' . $post->ID .'.html' ); } else { return $link; } } add_action( 'init', 'custom_book_rewrites_init' ); function custom_book_rewrites_init(){ global $mytypes; foreach( $mytypes as $k => $v ) { add_rewrite_rule( $v.'/([0-9]+)?.html$', 'index.php?post_type='.$k.'&p=$matches[1]', 'top' ); } }
说明:$mytypes数组存储需要更改固定链接的Custom Post Type和它们的固定链接前缀,例如type1这个自定义文章类型的固定链接将是http://www.domain.com/slug1/888.html