Thursday, September 13, 2018

How to set permalink to fetch all children custom posts with parent post in wordpress?

Leave a Comment

I create parent-child relationship for custom posts types.

Generic : www.example.com/parent/parent_post

Sample : www.example.com/projects/project-one

In above URL parent is a custom post type and parent post is its single post. I can show parents all posts and single post respectively as archive-parent.php and single-parent.php .

As I mentioned earlier, I create parent-child relationship and with child post that stores 'post_parent' as parent id.

Generic : www.example.com/child/parent_post/child_post

Sample : www.example.com/project_article/project-one/first-article

And for specific child post, URL will be as above.

Below code is for to get specific child post.And it's working fine.

function my_add_rewrite_rules() {     add_rewrite_tag('%child%', '([^/]+)', 'child=');     add_permastruct('child', 'child/%parent%/%child%', false);     add_rewrite_rule('^child/([^/]+)/([^/]+)/?','index.php?child=$matches[2]','top'); } add_action( 'init', 'my_add_rewrite_rules' );  function my_permalinks($permalink, $post, $leavename) {     $post_id = $post->ID;     if($post->post_type != 'child' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))         return $permalink;     $parent = $post->post_parent;     $parent_post = get_post( $parent );     $permalink = str_replace('%parent%', $parent_post->post_name, $permalink);     return $permalink; } add_filter('post_type_link', 'my_permalinks', 10, 3); 

Generic : www.example.com/child/parent_post

Sample : www.example.com/project_article/project-one

Now I want all child posts with parent post, as in above URL.

I am new to word-press Please guide.

1 Answers

Answers 1

Assuming parent as parent custom post type, child as child custom post type and hope you need child posts URL like http://www.example.com/parent/parent-post/child/child-post instead of http://www.example.com/child/parent-post/child-post.

Change your my_add_rewrite_rules() function to the following.

function my_add_rewrite_rules() {     add_rewrite_tag('%child%', '([^/]+)', 'child=');     add_permastruct('child', '/parent/%parent%/child/%child%', false);     add_rewrite_rule('^parent/([^/]+)/child/([^/]+)/?','index.php?child=$matches[2]','top'); } add_action( 'init', 'my_add_rewrite_rules' ); 

After updating don't forgot to flush permalinks via 'Settings > Permalinks'.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment