WordPress.org

Ready to get started?Download WordPress

Forums

Hierarchical custom post types - multiple post_name not queried correctly (2 posts)

  1. spindogs
    Member
    Posted 4 months ago #

    I have registered a custom post type with settings 'hierarchical' => true and 'supports' => array('title', 'editor', 'page-attributes')

    The intention is to use this post type for hierarchical posts much like the "page" post type.

    I have two posts with the following data:

    "Post 1"
    post_name: post-slug-here
    url: /custom-post-type/post-slug-here/

    "Post 2"
    post_name: post-slug-here
    url: /custom-post-type/parent-slug/post-slug-here/

    When I visit the URL /custom-post-type/post-slug-here/ you expect to see "Post 1", however it is actually "Post 2" being served up by WordPress.

    A quick dump of $wp_query shows that WordPress has found both "Post 1" and "Post 2" in its request, however it has incorrectly decided to use "Post 2" for the $post variable.

    The request should really order by post_parent ASC, this way always prioritising the post with post_parent = 0 over a subpage

  2. spindogs
    Member
    Posted 4 months ago #

    This bit of code certainly seems to help things:

    add_filter('request', 'hierarchical_post_fix');

    function hierarchical_post_fix($args) {
    
    	if (empty($args['post_type']) || $args['post_type'] != 'custom-post-type' || empty($args['name'])) {
    		return $args;
    	}
    
    	$args['orderby'] = 'parent';
    	$args['order'] = 'ASC';
    
    	return $args;
    
    }

Reply

You must log in to post.

About this Topic