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?
You have two options:
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 withpost_parent => 2
andpost_parent => 4
and finally merge all the results into a single array.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: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:
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
you can use other attributes (i.e.
$child->post_content
)…if you need to define post_type, then add this argument too :
&post_type=POST_TYPE_NAME