henrywright
henrywright

Reputation: 10240

Removing author base slug in WordPress without having to loop through all users

Default author links in WordPress look like this example.com/author/bobama. I am using the following 2 functions which remove the base slug /author/ making author links look like 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' );

Is there a way to remove the base slug /author/ without having to loop through all of the users? I have lots of users on my site and looping through them slows things down.

Upvotes: 0

Views: 627

Answers (1)

AmazingDreams
AmazingDreams

Reputation: 3204

I said something about pseudo code but I found it should actually be quite easy.

So here is how I'd do it:

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

Then for the user user registration you create a hook:

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

add_action('user_register', 'clear_author_rewrite_rules');

Upvotes: 2

Related Questions