将作者URL重写到Example.com/u/{User_id}/{Username}/

时间:2018-03-22 作者:Swen

我想重写作者URL以使用作者ID来确定显示的是谁的页面,然后在作者ID之后自动添加用户名。

URL应忽略用户名,以防止用户名更改破坏旧的配置文件链接,但也应重定向到当前使用的用户名。

example.com/u/{user_id}/            ->  example.com/u/{user_id}/{username}/
example.com/u/{user_id}/{anything}/ ->  example.com/u/{user_id}/{username}/
到目前为止,我有一些允许URL浏览到作者页面的代码,但在URL中的ID之后添加任何内容时都不起作用。

// It works!
example.com/u/{user_id}/

// Works, but shouldn\'t work
example.com/u/{username}/

// Doesn\'t work...
example.com/u/{user_id}/{anything}/
这是我当前的代码。

add_action(\'init\',\'change_user_permalink\');
function change_user_permalink() {  
    global $wp_rewrite; 
    $wp_rewrite->author_base = \'u\';
    $wp_rewrite->author_structure = \'/\' . $wp_rewrite->author_base . \'/%author%/\';

    add_rewrite_rule(\'^u/([0-9]+)/?$\', \'index.php?author=$matches[1]\', \'top\');
}

1 个回复
最合适的回答,由SO网友:Swen 整理而成

Figured it out!

/**
 * Replace %author_id% by author_id.
 *
 * @since   1.0.0
 * @param   string  $link
 * @param   int     $author_id
 */
add_filter( \'author_link\', \'wpse_298572_change_author_link\', 10, 2 );
function wpse_298572_change_author_link( $link, $author_id ) {
    $link = str_replace( \'%author_id%\', $author_id, $link );
    return $link;
}

/**
 * Rewrite the user link.
 *
 * @since   1.0.0
 */
add_action(\'init\', \'wpse_298572_rewrite_user_link\');
function wpse_298572_rewrite_user_link() {  
    global $wp_rewrite; 
    $wp_rewrite->author_base = \'u\';
    $wp_rewrite->author_structure = \'/\' . $wp_rewrite->author_base .\'/%author_id%/%author%/\';

    add_rewrite_rule(\'^u/([\\d]+)/?([A-Za-z0-9\\-\\_]+)\\/?$\', \'index.php?author=$matches[1]\', \'top\');
}

/**
 * Redirect to full user link.
 *
 * @since   1.0.0
 */
add_action(\'template_redirect\', \'wpse_298572_user_permalink_redirect\');
function wpse_298572_user_permalink_redirect() {    
    global $wp;

    // Check if on author page
    $author = get_query_var(\'author\');

    if ( !isset($author) ) {
        return;
    }

    preg_match("/\\/?u\\/([\\d]+)\\/?([A-Za-z0-9\\-\\_]+)?\\/?(.*)$/", $wp->request, $matches);

    if ( isset($matches[1]) && $user = get_user_by(\'ID\', $matches[1]) ) {       
        // Don\'t redirect if url already matches the correct name
        if ( $matches[2] == $user->user_nicename ) {
            return;
        }

        $author_permalink = get_author_posts_url($user->ID) . $matches[3];

        wp_safe_redirect($author_permalink, 301);
        exit();     
    }
}
结束

相关推荐