0

I'm using the following code to get a list of all the pages that are children of my project page and display them in a Recent Projects section of my template's footer element.

I've noticed that the get_page_children() method returns everything about that page - post_author, post_date, post_content, post_title, etc. Is there a way to limit this so that it only returns the post_title? Otherwise it is creating unnecessary overhead in querying all these other properties that aren't being rendered in the footer.

Also, is there a way to limit the number of objects returned? I only want the most recent four ordered by date descending.

    <h3>Recent Projects</h3>
    <ul class="footer-list">
    <?php
    // Set up the objects needed
    $my_wp_query = new WP_Query();
    $all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));

    // Get the page as an Object
    $projects =  get_page_by_title('Projects');

    // Filter through all pages and find Portfolio's children
    $projects_children = get_page_children( $projects->ID, $all_wp_pages );

    // echo what we get back from WP to the browser
    foreach ($projects_children as $project):
    ?>
        <li>
            <a href="<?php echo get_permalink($project); ?>"><?php echo var_dump($project);//echo $project->post_title; ?></a>
        </li>
    <?php endforeach; ?>
</ul>
1

You can just return the IDs, then get each title by the respective ID. And to restrict the query to four posts only, you can use posts_per_page.
I modified and optimized your above code a bit, so here it is:

<h3>Recent Projects</h3>
<ul class="footer-list"><?php
    $projects_page = get_page_by_title('Projects');

    $args = array(
        'post_type' => 'page',
        'post_parent' => $projects_page->ID,
        'ignore_sticky_posts' => true,
        'posts_per_page' => 4,
        'fields' => 'ids',
    );
    $projects = new WP_Query($args);

    foreach ($projects as $project) {
        ?><li>
            <a href="<?php echo get_permalink($project); ?>"><?php echo get_the_title($project); ?></a>
        </li><?php
    }
?></ul>
3

There isn't much overhead, you're hitting the database anyway. Just use array_map.

function get_titles($n) {
    return($n->post_title);
}

$titles_only = array_map("get_titles", $projects_children );

As for limiting and ordering, check out the Pagination Parameters (posts_per_page) and Order & Orderby Parameters of WP_Query.

Note: code is untested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.