0

What I want to achieve:

  1. Make Posts (post type 'post') hierarchical (Done - see code below)
  2. The child posts should have the following urls: domain.com/parent-slug/child-slug. This is exactly what happens when you use the build in hierarchy for pages but after making posts hierarchical the child posts have the url domain.com/child-slug/

Additional Info:

  • I am aware that this can be achieved with pages and custom post types but I have good reasons that I need it for the post post-type

What I did to achieve (1) and what seems to work:

add_filter( 'register_post_type_args', 'add_hierarchy_support', 10, 2 );
function add_hierarchy_support( $args, $post_type ){

    if ($post_type === 'post') { 

        $args['rewrite'] = array( 'slug' => get_post_parent()->post_name ); 
        $args['hierarchical'] = true;
        $args['supports'] = array_merge($args['supports'], array ('page-attributes') );
    }

    return $args;
}

add_filter( 'post_type_labels_post', 'change_post_label' );

function change_post_label($args) {
    $args->parent_item_colon = __( 'Parent Post:', 'textdomain' );
    return $args;
}

What I tried to achieve (2) and what doesn't work:

add_filter( 'post_link', 'filter_post_link', 10, 3 ); 
function filter_post_link( $permalink, $post, $leavename ) { 
    
    if( $post->post_parent ) {
        $parent_data = get_post($post->post_parent);
        $parent_slug = $parent_data->post_name;  
        $pos = strpos( $permalink, $post->post_name );
        $permalink = substr_replace( $permalink, $parent_slug .'/', $pos, 0 );
        return $permalink; 
    } else {
        return $permalink; 
    }
}; 

This creates the desired Post Link, but when visiting it I see a 404. I assume that I need to rewrite and redirect something here... So I tried to add a rewrite rule (but have difficulties to get my head around regex the rewrite API):


add_action('init', 'rewrite_post_slug');
function rewrite_post_slug() {

    if( $post->post_parent ) {
        $parent_data = get_post($post->post_parent);
        $parent_slug = $parent_data->post_name;  
        add_rewrite_rule('^' . $parent_slug . '/([^/]+)/?','index.php?name=$matches[1]','top');
    }
}

Any help is highly appreciated!

0

Your Answer

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