修改post
与修改不同的工作page
然后修改custom post type
permalink。下面介绍如何仅在模板代码中修改所有这些内容,并为整个页面提供自定义url结构。
修改自定义帖子类型permalink
add_action( \'init\', \'rewriteCustomPostUrls\' );
function rewriteUrls() {
global $wp_rewrite;
$version = \'/product/%product%/version/%version%\';
$wp_rewrite->add_rewrite_tag( "%product%", \'([^/]+)\', "product=" );
$wp_rewrite->add_rewrite_tag( "%version%", \'([^/]+)\', "version=" );
$wp_rewrite->add_permastruct( \'version\', $version, false );
}
修改后permalink
add_action( \'init\', \'rewritePostPermalink\' );
function rewritePostPermalink(){
global $wp_rewrite;
$wp_rewrite->permalink_structure = "/product/%product%/news/%postname%";
}
修改页面永久链接
add_action( \'init\', \'rewritePostPermalink\' );
public function rewritePagePermalink(){
global $wp_rewrite;
$wp_rewrite->page_structure = "/product/%product%/page/%pagename%";
}
之后需要过滤自定义变量,如
%product%
从…里面
get_permalink
回答对于每种类型、帖子、页面或自定义,都有不同的筛选器。小心点!
page_link
筛选器参数2不是与的$post
post_type_link
和
post_link
但是page\\u id。
add_filter( \'post_type_link\', \'permalinkRewrite\');
add_filter( \'post_link\', \'permalinkRewrite\' );
add_filter( \'page_link\', \'permalinkRewrite\' );
function permalinkRewrite( $permalink, $post ) {
if (gettype($post) === "integer"){
//page_link $post parameter is the ID instead of the object
$post = get_post($post);
}
//removed code - get your variable here
$product = "demoProduct";
if ( $product ) {
$permalink = str_replace( \'%product%\', $product->getSlug(), $permalink );
}
return $permalink;
}
最后,添加一些重写规则以捕获新的永久链接。
add_filter( \'rewrite_rules_array\', \'insertCustomRewriteRules\' );
function insertCustomRewriteRules( $rules ) {
$customRules = [];
$customRules[ \'product/([^/]+)/version/([^/]+)/?$\' ] = \'index.php?version=$matches[2]\'; //custom post type
$customRules[ \'product/([^/]+)/news/([^/]+)/?$\' ] = \'index.php?name=$matches[2]\'; //post
$customRules[ \'product/([^/]+)/page/([^/]+)/?$\' ] = \'index.php?pagename=$matches[2]\'; //page
return $customRules + $rules;
}