The get_children() WordPress PHP function retrieves all children of the post parent ID. It can be applied to pages, posts, and attachments.
Usage
get_children( $args, $output );
Example:
Input:
$args = array( 'post_parent' => 10, 'post_status' => 'publish', 'post_type' => 'attachment', ); $children = get_children( $args, ARRAY_A );
Output: Returns an associative array of children.
Parameters
$args(mixed): Optional. User defined arguments for replacing the defaults. Default:''$output(string): Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Post object, an associative array, or a numeric array, respectively. Default: OBJECT
More information
See WordPress Developer Resources: get_children()
Examples
Display the first image associated with the post
function display_first_image( $post_id ) {
$args = array(
'posts_per_page' => 1,
'order' => 'ASC',
'post_mime_type' => 'image',
'post_parent' => $post_id,
'post_status' => null,
'post_type' => 'attachment',
);
$attachments = get_children( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<img src="' . esc_url( wp_get_attachment_thumb_url( $attachment->ID ) ) . '" class="current" />';
}
}
}
Retrieve and re-key the array of the first image associated with the post
$args = array( 'posts_per_page' => 1, 'order' => 'DESC', 'post_mime_type' => 'image', 'post_parent' => $post->ID, 'post_type' => 'attachment' ); $get_children_array = get_children( $args, ARRAY_A ); $rekeyed_array = array_values( $get_children_array ); $child_image = $rekeyed_array[0];
Get all parent post IDs
$post_type = "post";
$post_status = "any";
$num_of_posts = -1;
$post_parent = 0;
$args = array('post_parent' => 0, 'post_type' => $post_type, 'numberposts' => $num_of_posts, 'post_status' => $post_status);
$parents = get_children($args);
foreach ($parents as $parent) {
echo "<br>ParentID: " . $parent->ID;
}
Get an array of child IDs only
$child_ids = get_children( [ 'post_parent' => $post_id, 'fields' => 'ids', ] );