How to display random child pages of a parent page in WordPress?

I am trying to display random child pages of a parent page, but I get random posts which I dont want to be included in the display area.

$my_query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1', 'pagename=guide') );

So, what I want is to display random child pages of a parent page who slug is guide, but instead I get random posts which is quite different from what I want. Any help would be appreciated. Thanks 🙂

Related posts

Leave a Reply

2 comments

  1. This is working for me. the post_type is the important part since otherwise it doesn’t seem WP will query against the pages. The post_parent should be the integer id of your page.

    $query = new WP_Query( array( 'orderby' => 'rand', 'posts_per_page' => 1, 'post_type' =>   'page', 'post_parent' => '2' )) ;
    if ( $query->have_posts() ) {
            echo '<ul>';
        while ( $query->have_posts() ) {
            $query->the_post();
            echo '<li>' . get_the_title() . '</li>';
        }
            echo '</ul>';
    } else {
        // no posts found
    }
    
  2. This worked for me:

    $my_wp_query = new WP_Query(); // Setup query object
    $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); // Get all pages
    $children = get_page_children( get_the_id(), $all_wp_pages); // Get the children pages from list of all pages
    $rand = rand(0, (count( $children) - 1)); // Count children and get a random number from that range
    print_r( $children[$rand]); // Print random child object
    

    Hope this helps!