• Resolved justinmaurerdotdev

    (@360zen)


    Okay, I’m back with one more question about getting child pages with get_pages().

    What I’m attempting to do is look at the current page’s child pages, if it has a child page with a specific taxonomy term, show the child instead of the parent.

    I’ve got this working almost 100% of the time, however, I just ran into a weird problem with the home page.

    Here’s how I’ve got the pages set up

    • Home (set to Front Page)
    • Alt Home Page*
    • About Us
    • Mission
    • Alt Mission Page*
    • History
    • Alt History Page*

    The get_pages code I’m using is this (you can see the rest of the code here):

    $args = array(
    		'child_of' => $pid,
    		'hierarchical' => 0,
    	);
    $children = get_pages($args);

    This setup is giving me exactly what I want on every page except for the home page. On the Mission page, I get the Alt Mission page (and other children of Mission page) in a list, check for the taxonomy term, and then shows the one with the taxonomy term (the Alt Mission page).

    On the home page, I get a list of all pages **including the home page itself** (because apparently WordPress sees them all as children of the home page), so when I search for the taxonomy term, it finds every page with this taxonomy term and then shows the content for (I’m assuming here) the last one it finds: the Alt History Page. If I add 'parent' => $pid, only top level pages are returned.

    So, my question is: How can I get only direct descendants of the Home page? Do I need to check is_front_page() and handle the Home page differently (provide a specific ID to use)?

    Any help would be much appreciated.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Johnathan

    (@jelyman)

    Perhaps with the homepage it would be better to check is_home_page() and if so, get_page_children().

    just a thought.

    Thread Starter justinmaurerdotdev

    (@360zen)

    Okay, I’ve solved it. I finally found this ticket where someone had the same problem. Ideally, you would is is_front_page() to handle the home page separately, but is_front_page() doesn’t work with the pre_get_posts hook. Instead, we can use this to get around that conditional:
    if ( $query->get('page_id') == get_option('page_on_front') )

    So, my code ended up being this:

    if ( $query->is_main_query() && !is_admin() && is_page() ) {
    		if ($query->get('page_id') == get_option('page_on_front')){
    			$id = get_option('page_on_front');
    		} else {
    			$id = get_queried_object_id();
    		}
    		if( $sitechild = site_child($id) ) {
    			$query->query_vars['page_id'] = $sitechild;
    		}
    	}

    Marking as resolved. Just wanted to leave this there in case anyone else is struggling with this like I was.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Another get_pages() question’ is closed to new replies.