How to show childs of certain custom post type in option list?

I have a custom post type and each post in this custom post type has many childs. I have a code that show every child that is child of the parent in child’s page. (parent: post 1 , childs: sub1-post, sub2-post. in sub1-post shows the sub1-post and sub2-post title and permalink)
the code is:

<?php
if ( $post->post_parent ) {
    $children = wp_list_pages( array(
        'title_li' => '',
        'child_of' => $post->post_parent,
        'echo'     => 0,
        'post_type' => 'mycustom'
    ) );
} else {
    $children = wp_list_pages( array(
        'title_li' => '',
        'child_of' => $post->ID,
        'echo'     => 0,
        'post_type' => 'mycustom'
    ) );
}

if ( $children ) : ?>
    <ul>
        
        <?php echo $children; ?>
    </ul>
<?php endif; ?>

Above code works perfect. now i want this code to show the list of children in a select and option mode.
Like:

<select>
<option>sub1-post</option>
<option>sub2-post</option>
</select>

But i want to echo dynamically. (like echo $children but in options).

Hope described well.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try to use wp_dropdown_pages instead of wp_list_pages .
This function does almost the same, but returns a dropdown, instead of list items. (do not need to echo select opening and closing tags separately)

if ( $post->post_parent ) {

   $children = wp_dropdown_pages( array(
        'name'      => 'your-name' // paste field name here
        'child_of'  => $post->post_parent,
        'post_type' => 'mycustom',
        'echo' => 0
   ));

} else {

   $children = wp_dropdown_pages( array(
        'name'      => 'your-name' // paste field name here
        'child_of'  => $post->ID,
        'post_type' => 'mycustom',
        'echo' => 0
   ));

}

if( $children ):
    echo $children;
endif;

Hope you already know that select is a form element and it keeps post id as option value, so you need to solve this manually if you want to redirect users to selected page id. (Code is not tested)

wp_dropdown_pages Code Reference


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x