I am using the get_pages function to display all pages within my custom post type, like this:

<?php
                $args = array(
                    'post_type'    => 'pcct_product',
                    'sort_column'  => 'post_title',
                    'menu_order'   => 'ASC'
                );

                $pages = get_pages($args); 
                foreach ( $pages as $pagg ) {
                $option = '<option value="' . get_page_link( $pagg->ID ) . '">';
                $option .= $pagg->post_title;
                $option .= '</option>';
                echo $option;
            }
            ?>

I want to be able to display ONLY the children in this custom post type. Has anyone got any suggestions of how I can go about that?

1 Answer
1

There are a few methods to return all child posts via get_pages().

One fairly straightforward method would be to get all of the IDs of the top-level parent posts, and then pass those IDs to the exclude parameter of get_pages():

<?php
// Get all top-level pcct_product posts;
// The 'parent' => 0 argument returns only
// posts with a parent ID of 0 - that is, 
// top-level posts
$parent_pcct_products = get_pages( array(
    'post_type'    => 'pcct_product',
    'parent'       => 0
) );
// Create an array to hold their IDs
$parent_pcct_product_ids = array();

// Loop through top-level pcct_product posts, 
// and add their IDs to the array we just
// created.
foreach ( $parent_pcct_products as $parent_pcct_product ) {
    $parent_pcct_product_ids[] = $parent_pcct_product->ID;
}

// Get all child pcct_product posts;
// passing the array of top-level posts
// to the 'exclude' parameter
$child_pcct_products = get_pages( array(
    'post_type'    => 'pcct_product',
    'exclude'      => $parent_pcct_product_ids,
    'hierarchical' => false
) );
?>

(Note: untested)

Edit

Try setting hierarchical tofalse`, since we’re excluding all top-level pages.

Leave a Reply

Your email address will not be published. Required fields are marked *