阿里云服务器

在做wordpress网站的时候,因为seo的原因,常常需要自定义固定链接格式。

我们添加的自定义文章类型链接结构都是固定的,如果要自定义修改链接可以使用插件:Custom Post Type Permalinks

如果不使用插件就可以在主题函数functions.php里面添加一下代码;

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

以上代码就可以输出形如 /book/123.html 的链接。请将代码中所有 book 替换为你的自定义文章类型。

如果你要同时定义多种自定义文章类型,可以使用下面的代码:

$mytypes = array(//根据需要添加你的自定义文章类型
	'type1' => 'slug1',
	'type2' => 'slug2',
	'type3' => 'slug3'
	);
add_filter('post_type_link', 'my_custom_post_type_link', 1, 3);
function my_custom_post_type_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', 'my_custom_post_type_rewrites_init' );
function my_custom_post_type_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' );
	}
}

 

相关阅读:
  • wordpress自定义文章类型置顶文章显示
  • wordpress自定义文章类型调用方法
  • wordpress自定义文章类型功能添加