'WordPress and WPML : rewrite slug + language = 404

I use WPML with WordPress. I created 3 custom post types for a project with students.

I would like for each student's page to add their names in the slug like that :

http://www.example.com/custom-post-type/firstname-lastname/post-title

To do this I added a tag %student% in the slug to add lastname and nickname of the student.

http://www.example.com/custom-post-type/%student%/post-title

Example of output :

http://www.example.com/free-topic/john-doe/the-age-of-participatory-culture

In the main language of my website all works well. But in other language I got 404 errors (in English with /en/ for example)

http://www.example.com/en/free-topic/john-doe/the-age-of-participatory-culture

To register my post types (example of one on my 3 custom post types) :

register_post_type( 'free-topic', array(
    'label'               => __( 'Sujets imposés', 'ctt' ),
    'description'         => __( 'Tous les sujets imposés', 'ctt' ),
    'public'            => true,
    'show_ui'           => true,
    'show_in_rest'      => true,
    'menu_position'     => 28,
    'menu_icon'         => 'dashicons-format-aside',
    'capability_type'   => 'post',
    'has_archive'       => false,
    'supports'          => array( 'thumbnail', 'editor', 'title', 'custom-fields' ),
    'with_front'        => false,
    'rewrite'           => array( 'slug' => 'sujet-libre/%student%' ),
));

In functions.php :

$post_types_name = array('free-topic', 'dissertation', 'curriculum-vitae');

function ccn_author_in_permalink($post_link, $post) {
    global $post_types_name;

    foreach ($post_types_name as $post_type_name) {
        $authordata = get_userdata($post->post_author);
        $author_name = $authordata->display_name;
        $author_name_final = sanitize_title($author_name);

        $post_link = str_replace('%student%', $author_name_final, $post_link);

        return $post_link;
    }
}

add_filter('post_type_link', 'ccn_author_in_permalink', 1, 2);

function ccn_rewrite_url() {
    add_rewrite_tag( '%student%','([^&]+)' );
}

add_action( 'init', 'ccn_rewrite_url' );

What did I forget to avoid 404 errors?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source