I am trying to change the default structure of the woocommerce product url to include the author username. The default url for woocommerce products in my installation is as so:
https://<site_url>/product/<product-name>
I want to change it to something like this:
https://<site_url>/product/<author-username>/<product-name>
This is the code that I have so far:
function so_pre_get_posts( $query ) {
// check if the user is requesting an admin page
// or current query is not the main query
if ( is_admin() || ! $query->is_main_query() ){
return;
}
//since the author is not included in woocommerce query vars add author username to query_vars
$post_type = get_query_var( 'post_type' );
if($post_type === 'product'){
$post_name = get_query_var( 'name');
if ( $post = get_page_by_path($post_name,OBJECT,'product') ){
$id = $post->ID;
$author_id = get_post_field( 'post_author', $id );
$author = get_userdata($author_id);
$author_username = $author->user_login;
$query->set( 'seller',$author_username);
}else{
return;
}
}
}
//add rewrite rules
function so_rewrite_tag_rule() {
add_rewrite_tag( '%seller%', '([^&]+)' );
add_rewrite_rule('^product/([^/]+)/([^/]+)/?$', 'index.php?seller=$matches[1]&name=$matches[2]','top');
flush_rewrite_rules();
}
add_action( 'pre_get_posts', 'so_pre_get_posts', 1 );
add_action('init', 'so_rewrite_tag_rule', 10, 0);
However when I visit the product page for any product it still resolves to the default woocommerce permalink structure. I made sure to flush the permalinks in my code so I have no idea what the issue is.