修改URL结构通常由两部分组成:一部分修改用代码生成的URL,另一部分处理新结构的传入URL。后一部分是通过修改重写规则来完成的。
我刚刚在中详细解释了相关的重写功能a response to a similar question, 下面是针对您的情况的代码:
add_action( \'init\', \'wpa5444_init\' );
function wpa5444_init()
{
// Remember to flush the rules once manually after you added this code!
add_rewrite_rule(
// The regex to match the incoming URL
\'companies/tasks/([^/]+)/?\',
// The resulting internal URL: `index.php` because we still use WordPress
// `pagename` because we use this WordPress page
// `category_slug` because we assign the first captured regex part to this variable
\'index.php?pagename=companies&category_slug=$matches[1]\',
// This is a rather specific URL, so we add it to the top of the list
// Otherwise, the "catch-all" rules at the bottom (for pages and attachments) will "win"
\'top\' );
}
add_filter( \'query_vars\', \'wpa5444_query_vars\' );
function wpa5444_query_vars( $query_vars )
{
$query_vars[] = \'company_slug\';
return $query_vars;
}
第一部分,编写与这个新的漂亮结构相匹配的URL,不是捆绑在一个地方,而是分布在生成URL的所有函数上。您需要自己编写一个函数来处理您的案例,因为您生成了一个页面URL并向其中添加了类别部分。它可能是这样的:
function wpse5444_company_link( $category_slug = \'\' )
{
$company_page_id = 42; // Somehow convert the page slug to page ID
$link = get_page_link( $company_page_id );
if ( $category_slug ) {
// trailingslashit() makes sure $link ends with a \'/\'
$link = trailingslashit( $link ) . \'tasks/\' . $category_slug;
// user_trailingslashit() adds a final \'/\' if the settings require this,
// otherwise it is removed
$link = user_trailingslashit( $link );
}
return $link;
}