dimanche 3 juillet 2016

Wordpress custom post type rewrite rule matches all pages

I've created a custom post type with a rewrite to use the grandparent relationship as the URL like so:

function cpt_child(){
 $args = array(
  //code
  'rewrite' => array( 'slug' => '%grandparent%/%parent%', 'with_front' => false),
 );
 register_post_type( 'child', $args );
}
add_action( 'init', 'cpt_child' );

Then I update the permalink:

add_filter( 'post_type_link', 'filter_the_post_type_link', 1, 2 );
function filter_the_post_type_link( $post_link, $post ) {
  switch( $post->post_type ) {
    case 'child':
            $post_link = get_bloginfo( 'url' );
            $relationship_child = p2p_type('children_to_parents')->get_adjacent_items($post->ID);
            $parent = $relationship['parent']->post_name;
            $relationship_parent = p2p_type('parents_to_grandparents')->get_adjacent_items($parent['parent']->ID);
            $grandparent = $relationship_parent['parent']->post_name;
            $post_link .= "/{$grandparent}/";
            $post_link .= "{$parent}/";
            $post_link .= "{$post->post_name}";
    break;
  }
  return $post_link;
}

This all works great, but unfortunately the rewrite rule matches regular pages as well which makes them 404.

I can prevent this by adding a custom slug, for example 'relationship': http://example.com/relationship/grandparent/parent/child

But I'd really like to use http://example.com/grandparent/parent/child and have it not break regular pages.

I might have to resort to using non native Wordpress rewrites using htaccess.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire