Rewrite URL – insert custom variables as a directory path

I’m trying to re-write permalink structure with my own custom url in WordPress for a Divi Theme “project”

I have already changed the “Divi slug” from “project” to “prodotti” so currently, the URL appears like this:

http://www.example.com/prodotti/%postname%/

with my custom function

function custom_post_name() {
    return array(
        'feeds' => true,
        'slug' => 'prodotti',
        'with_front' => false,
    );
}
add_filter('et_project_posttype_rewrite_args', 'custom_post_name');

I want to add to these urls a variable, that reside for each post in post_metadata, in order to build a url like:

http://www.example.com/prodotti/<mypostoptionvalue>/%postname%/

ex:

http://www.example.com/prodotti/AEX1102/%postname%/
http://www.example.com/prodotti/AEX1103/%postname%/
http://www.example.com/prodotti/AEX1104/%postname%/

Is there a way to achieve this kind of behavior?

I have done many test using, {$permastruct}_rewrite_rules, page_rewrite_rules, post_rewrite_rules and more starting from: https://codex.wordpress.org/Class_Reference/WP_Rewrite without results.

1 Answer
1

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

Leave a Comment