Display posts with author in the url with custom post types

You can use the %author% tag in the rewrite property in register_post_type(). However, although the rewrite rules are added (after they’re flushed) – WordPress doesn’t replace the tag with its appropriate value when generating the permalink of your post type. For instance you end up with the permalink www.example.com/%author%/gallery-name

The following replaces %author% with the appropriate value:

add_filter('post_type_link', 'wpse73228_author_tag',10,4);
function wpse73228_author_tag($post_link, $post, $leavename, $sample){

    if( 'gallery' != get_post_type($post) )
        return $post_link;

    $authordata = get_userdata($post->post_author);
    $author = $authordata->user_nicename;

    $post_link = str_replace('%author%', $author, $post_link);

    return $post_link;
}

Leave a Comment