0
votes

I want to change the default post permalink structure from (example.com/post-name) to (example.com/author_firstname-author_lastname/post-name).

I tried to add a new rewrite tag which I could use in the custom permalink structure to use the author first name and last name in the URL but it didn't work (404 error page).

add_filter('post_link', 'pauthor_permalink', 10, 3);
add_filter('post_type_link', 'pauthor_permalink', 10, 3);

function pauthor_permalink($permalink, $post_id, $leavename) {
    add_rewrite_tag( '%pauthor%', '(.+)', 'pauthor=' );
    if (strpos($permalink, '%pauthor%') === FALSE) return $permalink;

    // Get post
        $post = get_post($post_id);
        if (!$post) return $permalink;

        // Get Author Data
        $post_author = get_post_field( 'post_author', $post->ID );
        $user_info = get_userdata($post_author);
        $first_name = $user_info->first_name;
        $last_name = $user_info->last_name;
        $pauthor = $first_name.'-'.$last_name;


    return str_replace('%pauthor%', $pauthor, $permalink);
}   

any help!?

1

1 Answers

0
votes

Changing the Permalink structure in wordpress can be done without any sort of php.

See Settings > Permalinks

https://codex.wordpress.org/Settings_Permalinks_Screen


The structure you are looking for appears to be /%author%/%postname%/

More tags can be found here: https://codex.wordpress.org/Using_Permalinks#Structure_Tags


Creating Custom Tags

You can create custom tags by creating a new taxonomy with 'rewrite' => true, for example:

add_action( 'init', 'my_rating_init' );

function my_rating_init() {
    if ( ! is_taxonomy( 'rating' ) ) {
        register_taxonomy( 
            'rating', 
            'post', 
            array( 
                'hierarchical' => FALSE, 
                'label' => __( 'Rating' ),  
                'public' => TRUE, 
                'show_ui' => TRUE,
                'query_var' => 'rating',
                'rewrite' => true 
            ) 
        );
    }
}

Source: https://wordpress.stackexchange.com/questions/168946/add-more-structure-tag-to-permalink