0

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.

1 Answer 1

1

No need to add additional rewrite rule for that, WooCommerce already provide a way to mess with product permalink. Visit Wp Admin > General > Permalink page, and use /product/%author%/ as Product permalinks value. This will organize the product url as you need.

However, WooCommerce won't replace %author% tag with product's author as like we see with post permalink, so you have to replace the tag using post_type_link filter.

// replace %author%

add_filter( 'post_type_link', 'wpse_post_type_link', 20, 2 );

function wpse_post_type_link( $permalink, $post ) {
    if ( 'product' === $post->post_type && false !== strpos( $permalink, '%author%' ) ) {
        $author = get_the_author_meta( 'user_nicename', $post->post_author );
        $permalink = str_replace( '%author%', $author, $permalink );
    }

    return $permalink;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.