Support » Fixing WordPress » Use WP_Query to get child pages of a page

  • Resolved Tatiane Pires


    I know that there are several other ways to query for pages. And I want to code it, so means no plugins.

    I’m using WP_Query because I can use functions like the_ID(), the_permalink(), the_post_thumbnail() and the_excerpt() in the loop.

    My last attempt so far was:

    $pageArgs = wp_parse_args($query_string);
    $pageArgs['post_type'] = 'page';
    $pageArgs['post_status'] = 'publish';
    $pageArgs['child_of'] = 675;
    $pageArgs['sort_column'] = 'menu_order';
    $pageArgs['sort_order'] = 'ASC';
    $pageQuery = new WP_Query($pageArgs);

    It doesn’t seem to be relevant to include or not “$pageArgs = wp_parse_args($query_string);”, I have the same results.

    If I query the database on phpMyAdmin, I get exactly the results I need with:
    SELECT * FROM wp_posts WHERE (post_parent = 675) AND (post_status) = ‘publish’

    But it causes an error if I try to use the results of $wpdb->get_results (see below) on the loop:

    $pageQuery = $wpdb->get_results("SELECT * FROM wp_posts WHERE (post_parent = 675) AND (post_status) = 'publish'");
    while ($pageQuery->have_posts()) : $pageQuery->the_post();

    “Fatal error: Call to a member function have_posts() on a non-object”

    I need some help, please. =)

Viewing 1 replies (of 1 total)
  • I can’t believe the answer is so damn simple!

    But I only found it digging into some pages I’ve previously developed. After I found setup_postdata() in one of these pages, all I needed was to check

    global $wpdb;
    global $post;
    $pageQuery = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE post_parent = 675 AND post_status = 'publish'";
    $pages = $wpdb->get_results($pageQuery);
    foreach($pages as $post) : setup_postdata($post);

Viewing 1 replies (of 1 total)
  • The topic ‘Use WP_Query to get child pages of a page’ is closed to new replies.