WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] get_posts() sort by parent/child relationship (2 posts)

  1. ThomasG
    Member
    Posted 1 year ago #

    Hello!

    I've been tasked to create a "print all" page-template for WordPress. Displaying the title, 2 custom properties, and the entire content of every page in the WordPress install.

    In order to accomplish this, i've used get_posts(), but it seems be lacking when trying to sort the output.

    The desired output (as seen in admin):
    Subpage 1
    - Subpage 1.1
    -- Subpage 1.1.1
    - Subpage 1.2
    Subpage 2
    - Subpage 2.1
    - Subpage 2.2

    The output get_posts() gives me:
    Subpage 1
    - Subpage 1.1
    - Subpage 1.2
    Subpage 2
    - Subpage 2.1
    -- Subpage 1.1.1
    - Subpage 2.2

    The code:

    $args = array(
    'posts_per_page' => -1,
    'orderby' => 'menu_order',
    'exclude' => array(2, 70, 76),
    'post_type' => 'page',
    'post_status' => 'publish'
    );
    $listallprint = get_posts($args);
    
    foreach ($listallprint as $page_item) : setup_postdata($page_item);
    	$kontor = get_post_meta($page_item->ID, 'kontor', true);
    	$projektleder = get_post_meta($page_item->ID, 'projektleder', true);
    ?>
    <div class="list-page">
    	<?php
    	if($page_item->post_parent != 0) {
    		echo '<h2 class="title">' . get_the_title($page_item->ID) . '</h2>';
    	}
    	else {
    		echo '<h1 class="title">' . get_the_title($page_item->ID) . '</h1>';
    	}
    
    	if($kontor != '' || $projektleder != '') {
    		echo '<p class="projektspec">';
    			echo $kontor . '<br />';
    			echo $projektleder;
    		echo '</p>';
    	}
    	?>
    	<p>
    		<?php the_content(); ?>
    	</p>
    </div><!-- /.list-page -->
    <?php endforeach; ?>

    The question:
    How do i sort the array properly, to display each related child-node beneath its parent? I've tried orderby => 'menu_order parent' and 'parent' also, to no avail.

    Any help or direction is much appreciated, thanks.

    // Thomas G

  2. ThomasG
    Member
    Posted 1 year ago #

    Hello again!

    I actually ended up solving this one myself, by using a different approach.

    Instead of using get_posts(), i used get_pages() which supports a hierarchical tree structure, thus outputting the array as desired.
    I hope that will help someone. :)

    // Thomas G

Topic Closed

This topic has been closed to new replies.

About this Topic