title: Wordpress permalink rewrite for custom taxonomy and post type that uses parent and child terms hierarchy in URLs
body: <p>I have registered a custom taxonomy and post type to handle the display of photo galleries on my website. I am needing to setup the permalinks to look like this: domain.com/photos/region/country/location or domain.com/photos/country/location depending on the selected terms for each post type. The region and country terms would be dependent on if the parent terms are <strong>Canada</strong>, <strong>United States</strong>, or <strong>World</strong>.</p>
  <p>An example:</p>
  <ul>
  <li>Canada (parent term)
  <ul>
  <li>Alberta (child term)</li>
  </ul>
  </li>
  <li>United States (parent term)
  <ul>
  <li>Arizona (child term)</li>
  </ul>
  </li>
  <li>World (parent term)
  <ul>
  <li>France (child term)</li>
  </ul>
  </li>
  </ul>
  <p><strong>Register taxonomy code</strong></p>
  <pre><code>register_taxonomy( 'photo_galleries', array( 'photos' ),
    array(
      'hierarchical' =&gt; true,
      'labels' =&gt; $labels,
      'show_ui' =&gt; true,
      'show_admin_column' =&gt; true,
      'query_var' =&gt; true,
      'rewrite' =&gt; array(
        'slug' =&gt; 'galleries',
        'with_front' =&gt; false
      ),
  ));
  </code></pre>
  <p><strong>Custom post type arguments</strong></p>
  <pre><code>$args = array(
    'supports' =&gt; $supports,
    'labels' =&gt; $labels,
    'hierarchical' =&gt; true,
    'public' =&gt; true,
    'rewrite' =&gt; array(
      'slug' =&gt; 'photos',
      'with_front' =&gt; false
    ),
    'menu_position' =&gt; 5,
    'menu_icon' =&gt; 'dashicons-format-gallery',
    'has_archive' =&gt; true,
  );
  register_post_type( 'photos', $args );
  </code></pre>
  <p><strong>Galleries post_type_link function</strong></p>
  <pre><code>function galleries_post_type_link( $url, $post ) {
    if ( $post-&gt;post_type == 'photos' ) {
      global $post;
      $terms = get_the_terms( $post-&gt;id, 'photo_galleries' );
      $term = $terms[0]-&gt;slug;
      $url = str_replace('photos/', 'photos/' . $term . '/', $url);
    }
    return $url;
  }
  add_filter('post_type_link', 'galleries_post_type_link', 10, 4);
  </code></pre>
  <p>Right now this code is showing the following permalink structure in the admin panel custom post editor: <strong>domain.com/photos/france/bordeaux/</strong>. This post has a parent term of <strong>World</strong> and a child term of <strong>France</strong>. The term <strong>France</strong> has been set to primary, but making <strong>World</strong> the primary term has no effect on the permalink. As you can see, France is only being used in the permalink.</p>
  <p>I have tried the following custom permalink structures with no success: <code>/%category%/%postname%/</code> and <code>/%postname%/</code>.</p>
  <p>Any help is greatly appreciated.</p>
  <p>Cheers,</p>