Rewrite URL – insert custom variables as a directory path

I think you wanna do something like this:

add_action('init', 'my_rewrite');
function my_rewrite() {
  global $wp_rewrite;
  // Your desired structure
  $permalink_structure="/prodotti/%my_custom_variable%/%postname%/"
  // add the custom variable to wp_rewrite tags
  $wp_rewrite->add_rewrite_tag("%my_custom_variable%", '([^/]+)', "my_custom_variable=");
  // Here you need to know the name of the custom post type you want the permalink structure to be used on
  $wp_rewrite->add_permastruct('custom_post_type_name', $permalink_structure, false);
}

This should change your permalink structure for the post type.
If you now visit a post named “foobar” (in wp admin) it should show you a permalink of:

/prodotti/%my_custom_variable%/foobar/

All you need to do now is to intercept the permalink creation via the hook “post_type_link” and replace the string “%my_custom_variable%” with whatever you want, something like this:

add_filter('post_type_link', 'intercept_permalink', 10, 3);
function intercept_permalink ($permalink, $post, $leavename) {
  //check if current permalink has our custom variable
  if ( strpos($permalink, '%my_custom_variable%') !== false ) {
    //get this post's meta data with $post->ID
    $my_str = get_post_meta($post->ID, 'meta_key');
    //maybe check if post meta data is legit and perhaps have some kind of fallback if it's empty or something
    //Then we just replace the custom variable string with our new string
    $permalink = str_replace('%my_custom_variable%', strtolower($my_str), $permalink);
  }
  return $permalink;
}

I haven’t tested this specific code but I have recently done similar things in one of my projects