删除WordPress中的作者基础slug而无需遍历所有用户

时间:2014-03-15 09:48:21

标签: php wordpress rewrite

WordPress中的默认作者链接如下所示example.com/author/bobama。我正在使用以下2个函数删除基本段/author/,使作者链接看起来像example.com/bobama

function my_remove_author_base_function() {
    global $wp_rewrite;

    $wp_rewrite->author_base = '';
    $wp_rewrite->author_structure = '/%author%';
}
add_action( 'init', 'my_remove_author_base_function' );

-

function author_base_rewrite_rules_function( $author_rewrite ) {
    global $wpdb;

    // Reset the author rewrite rules
    $author_rewrite = array();

    // Grab the user_nicename column
    $authors = $wpdb->get_col( "SELECT user_nicename FROM {$wpdb->users}" );

    // Loop through every user and create corresponding rewrite rules
    foreach( $authors as $author ) {
        $author_rewrite["({$author})/page/?([0-9]+)/?$"] = 'index.php?author_name=$matches[1]&paged=$matches[2]';
        $author_rewrite["({$author})/?$"] = 'index.php?author_name=$matches[1]';
    }

    // Return new rewrite rules
    return $author_rewrite;
}
add_filter( 'author_rewrite_rules', 'author_base_rewrite_rules_function' );

有没有办法删除基本slug /author/而无需遍历所有用户?我的网站上有很多用户,循环浏览它们会减慢速度。

1 个答案:

答案 0 :(得分:2)

我说了一些伪代码,但我发现它实际上应该很容易。

所以我就是这样做的:

function author_base_rewrite_rules_function( $author_rewrite ) {
    global $wpdb;

    // Check cache and return if exists
    // get_transient returns FALSE if the key is not set or is expired
    if(($author_rewrite = get_transient('author_rewrite')) !== FALSE) {
        return $author_rewrite;
    }

    // Reset the author rewrite rules
    $author_rewrite = array();

    // Grab the user_nicename column
    $authors = $wpdb->get_col( "SELECT user_nicename FROM {$wpdb->users}" );

    // Loop through every user and create corresponding rewrite rules
    foreach( $authors as $author ) {
        $author_rewrite["({$author})/page/?([0-9]+)/?$"] = 'index.php?author_name=$matches[1]&paged=$matches[2]';
        $author_rewrite["({$author})/?$"] = 'index.php?author_name=$matches[1]';
    }

    // Set cache for one hour
    set_transient('author_rewrite', $author_rewrite, 60 * 60); 

    // Return new rewrite rules
    return $author_rewrite;
}

add_filter( 'author_rewrite_rules', 'author_base_rewrite_rules_function' );

然后,对于用户用户注册,您将创建一个钩子:

function clear_author_rewrite_rules( $user_id = NULL) {
    delete_transient('author_rewrite');
}

add_action('user_register', 'clear_author_rewrite_rules');