3
votes

Hard to define the Title of this Question....

I want to create a nice readable permalink structure for my 2 custom post types (CPT). My first CPT "family" has the following rewrite-slug "family/%postname%" (all works fine)

The second CPT "childs" has a metabox where I can select the parent_id-field by choosing a CPT "family" where the child-CPT belongs to. That also works great.

Now I set the rewrite-slug for "childs" to "%parent_post_url%/child/%postname%" so that I can get the following URL "family/the-griffons/child/peter" . But when I call this URL wordpress displays a not-found-page. The crazy thing is that if I set the rewrite-slug hard to "family/the-griffons/child/%postname%" I can call the URL (both URLs are the same!!!)

So why toes WP throws an error when I try to get the URL dynamically but not when I hardcode the URL??

1
To implement ur task, u should use Custom_Taxonomies or set hierarchical option to ur CPT, then it should work like default post_type Page in wordpress. And about using rewrite-slug %parent_post_url% - WP have not such default rewrite-slug, that's why u have 404 error. Please post PHP code for ur CPT.c0ns0l3

1 Answers

1
votes

The child-parent relationship you think you have is not quite there. Based on what you've told us so far, it seems that all you have is a custom field denoting the "pseudo-parent" id. So what your question should really read is

How do I rewrite the first part of the cpt url, based on the cpt custom field value ?

because, as far as wordpress is concerned in your case, that's all that "parent id" really is- a custom field value.

you can try following the last part(Part 3.) of this tutorial, keeping in mind, that you'll want the actual path of the url of the "parent id" and not the cf "parent id" value itself, you'll have to implement something along the lines of:

$parent_id = get_post_meta($post_id, "your_cf_key_for_parent_id", true);
$full_parent_post_url =  parse_url( get_permalink( $parent_id ) );
$parent_post_url =  $full_parent_post_url['path'];
if(!$parent_post_url) { $parent_post_url = "default-fallback" }
$permalink = str_replace(‘%parent_post_url%’, $parent_post_url, $permalink);
return $permalink;

another relevant stackexchange answer:

using-custom-fields-in-custom-post-type-url

BUT as @c0ns0l3 mentioned using custom taxonomies IS the proper way to go about this.