wp_list_pages doesn't work in hierarchical custom post type
-
16-10-2019 - |
Question
I've been bashing my head against my desk all afternoon trying to figure this out. I've got a custom post type all set up, with hierarchical set to "true" and I can assign parents and see the relationship in the back end. Which is great.
Except I want to list the children (and siblings) of my special new post type. I found this code
<?php if($post->post_parent)
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
else
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
if ($children) { ?>
<ul>
<?php echo $children; ?>
</ul>
<?php } ?>
which works perfectly when I put it into a page template for pages. But it returns squat for the custom post template. I thought "$post->post_parent)" might be the issue -- but it's not:
<h1 class="page-title"><a href="<?php echo get_permalink($post->post_parent) ?>" title="<?php printf( __( 'Return to %s', 'your-theme' ), wp_specialchars( get_the_title($post->post_parent), 1 ) ) ?>" rev="attachment"><span class="meta-nav">« </span><?php echo get_the_title($post->post_parent) ?></a></h1>
(lifted from an attachment template) does give me a back link to the parent. -- so maybe it has something to do with wp_list_pages? Maybe it's something else? I'd appreciate any ideas.
Thanks in advance,
Martin
Solution
As name hints wp_list_pages()
is intended for use with pages. As in "a page page". It uses get_pages()
internally, which has post_type
argument that defaults to page
.
I am not sure at all this is supposed to work for non-pages, but you can try to pass your custom post type as that post_type
argument.
OTHER TIPS
I'm trying to do something very similar. Here's what I've got so far, using a custom post type of "product":
$children = wp_list_pages("sort_column=menu_order&title_li=&child_of=".$post->post_parent."&post_type=productE&echo=0")
this generates the list; unfortunately the links are generated as
siteurl.com/parent-product/child-page
which causes a 404. Doing a view from the edit screen shows the desired url as
siteurl.com/?product=child-page
I'm using the More Types plugin, so set the permalink base for the custom post type to product
, using the advanced tab while editing the type.
This did the trick for me.
Hmm... Another consideration when using wp_list_pages for custom post types is making sure you register the custom post type with the 'capability_type' => 'page' NOT 'post'.... eg:
register_post_type( 'mycpt',
array(
'labels' => array(
'name' => __( 'MyCPTs' ),
'singular_name' => __( 'MyCPT' )
),
'public' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'capability_type' => 'page',
'menu_position' => 20,
'hierarchical' => true,
'rewrite' => true,
'supports' => array('title','editor','page-attributes')
)
);
flush_rewrite_rules();