I have parent posts (custom post type hierarch=true) with ID 1, 2, 3, 4.

The parent posts with ID 2 and 4 have child pages.

I need to retrieve only posts 2 and 4 and all of their child pages.

Something like this

$argsch = array('orderby' => 'date','order' => 'DESC','post_type' => 'products', 'include' => '2, 4');
$childs = get_posts($argsch);

How can I edit this to return child pages of the included id's?

link|improve this question

60% accept rate
feedback

2 Answers

up vote 1 down vote accepted

You have two options:

  1. Call get_posts multiple times: one for the parent pages using post__in => array(2,4), and two for the child pages of each parent with post_parent => 2 and post_parent => 4 and finally merge all the results into a single array.

  2. Write directly your SQL query and use $wpdb->get_results. See this article for an example. In your case it would be something similar to the following (not tested) code:

    $query_sql = "
        SELECT *
        FROM $wpdb->posts
        WHERE post_type = 'products'
        AND (ID IN (2,4) OR post_parent IN (2,4))
        ORDER BY post_date DESC
    ";
    $query_result = $wpdb->get_results($query_sql, OBJECT);
    
link|improve this answer
the first on is bad, becouse I dont know exact count of Ids there might be. The second on seem good to me. Ill try. – jam Nov 22 '11 at 11:48
This was the greatest! – jam Nov 22 '11 at 12:08
feedback
$args = array('orderby' => 'date','order' => 'DESC','post_type' => 'products', 'include' => '2, 4');

// get the 2 and 4 posts
$children = get_posts($args);

// get the children of 2, and merge arrays
$children = array_merge($children,get_posts(array('orderby' => 'date','order' => 'DESC','post_type' => 'products','post_parent'=>2)));

// get the children of 4, and merge arrays
$children = array_merge($children,get_posts(array('orderby' => 'date','order' => 'DESC','post_type' => 'products','post_parent'=>4)));

foreach($children as $child){
    // etc
}

Although it would be much much easier/faster if you could tag them in a custom taxonomy or identify them some other way so that you were only needing to look for one thing, rather than 3 things.

e.g. if we had a custom taxonomy 'highlighted_products' we might do:

$children = get_posts('post_type' => 'products', 'orderby' => 'date','order' => 'DESC','highlighted_products' => 'example_page');
foreach($children as $child){
    // etc
}

Which would be far more flexible, less prone to errors ( ID 2 and 4 might change! Don't hardcode ), and it's a lot faster to do, no raw SQL or multiple queries. Not to mention that you now have a nice user friendly UI in the backend where you just tag a products post and it appears in the right place

link|improve this answer
Thank you for your contribution! Direct SQL query runs smootly – jam Nov 22 '11 at 12:09
feedback

Your Answer

 
or
required, but never shown

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