Rewrite category slug

It can be done by writing a code on post_link filter. This filter allows you to change the final post link.

Since you are showing categories in your permalink, so I am assuming that your permalink structure contains %category% in it.

Below code will help you to get links the way you want.

add_filter( 'post_link', 'wdm_change_category_permalink_structure', 10, 3 );

function wdm_change_category_permalink_structure( $post_link, $post, $leavename ) {

    $array_of_cats_to_be_replaced = array( 'europe', 'usa' ); //array of category slugs. Add more slugs here

    $get_permalink_structure = get_option( 'permalink_structure' );

    if ( strpos( $get_permalink_structure, '%category%' ) !== false ) {

        $cats = get_the_category( $post->ID ); //get categories assocaited with the post

        if ( $cats ) {

            usort( $cats, '_usort_terms_by_ID' ); // order by ID  

            $category_object = get_term( $cats[0], 'category' ); //Take first category

            $category = $category_object->slug; //Get slug of category

            if ( in_array( $category, $array_of_cats_to_be_replaced ) ) { //If category we want is in the array
                $rewritecode = array(
                    '%year%',
                    '%monthnum%',
                    '%day%',
                    '%hour%',
                    '%minute%',
                    '%second%',
                    $leavename ? '' : '%postname%',
                    '%post_id%',
                    '%category%',
                    '%author%',
                    $leavename ? '' : '%pagename%',
                );
                $rewritereplace = array(
                            $date[0],
                            $date[1],
                            $date[2],
                            $date[3],
                            $date[4],
                            $date[5],
                            $post->post_name,
                            $post->ID,
                            'news/view', //Replace category with news/view
                            $author,
                            $post->post_name,
                );

                $post_link = home_url( str_replace( $rewritecode, $rewritereplace, $get_permalink_structure ) );
                $post_link = user_trailingslashit( $post_link, 'single' );
            }
        }
    }
    return $post_link;
}

Hope it helps 🙂

Leave a Comment