3

Trying to get my permalink and url structures to behave nicely.

I have a Custom Post Type called Diseases.

This post type is hierarchical with parent and child relationships.

I have another CPT called Content, and I'm using ACF relationships to connect these posts with Diseases.

Functionally this all works fine, I can even rewrite the Content URL to something like:

/diseases/%diseases%/%content%

This works great, at least until I try to go to a connected post that has a Parent and Grandparent Disease structure e.g.

/diseases/cancer/lung-cancer/content

The URL is what I want but I get a 404.

I'm having difficulty in getting the rewrite rules to point this new URL structure to the Content post type.

Here are my current rules:

function my_add_rewrite_rules() {
  global $wp_rewrite;
  add_rewrite_tag('%content%', '([^/]+)', 'content=');
  add_permastruct('content', '/diseases/%diseases%/%content%', false);
  add_rewrite_rule('^diseases/([^/]+)/([^/]+)/?','index.php?content=$matches[2]','top');
}
add_action( 'init', __NAMESPACE__ . '\\my_add_rewrite_rules' );

And my permalink logic:

function my_permalinks($permalink, $post, $leavename) {

  $post_id = $post->ID;

  if($post->post_type != 'content' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft'))):
    return $permalink;
  endif;

  $parent = $post->post_parent;
  $parent_post = get_post( $parent );

  $grandparent = $parent_post->post_parent;
  $grandparent_post = get_post( $grandparent );

  if( $grandparent != 0 ):
    $struct = $grandparent_post->post_name.'/'.$parent_post->post_name;
  else:
    $struct = $parent_post->post_name;
  endif;

  $permalink = str_replace('%diseases%', $struct, $permalink);

  return $permalink;
}
add_filter('post_type_link', __NAMESPACE__ . '\\my_permalinks', 10, 3);

Help much appreciated.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.