get_children()WP 2.0.0

Retrieve all children (attachments, revisions, or sub-pages) of the post parent ID. It works similar to get_posts().

No Hooks.

Return

WP_Post[]|Array[]|Int[]. Array of post objects, arrays, or IDs, depending on $output.

Usage Template

$childrens = get_children( [
	'post_parent' => 0,
	'post_type'   => 'any',
	'numberposts' => -1,
	'post_status' => 'any'
] );

if( $childrens ){
	foreach( $childrens as $children ){
		// output
	}
}

Usage

get_children( $args, $output );
$args(mixed)
User defined arguments for replacing the defaults.
Default: ''
$output(string)
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

Parameters of $args

See get_posts() for a full list of $args parameters.

In addition to this list of $args parameters, you can use any of the WP_Query parameters.

numberposts(int)
Number of child posts to retrieve. -1 — all of them.
Default: -1
post_parent(int)
ID of the post to get its children. Pass 0 to get attachments without parent. Pass null to get any child regardless of parent.
post_type(string)
Any value from post_type column of the posts table, such as attachment, page, or revision; or the keyword any.
Default: any
post_status(string)
Any value from the post_status column of the wp_posts table, such as publish, draft, or inherit; or the keyword any.
Default: any
post_mime_type(string)
A full or partial mime-type, e.g. image, video, video/mp4, audio which is matched against a post's post_mime_type field.
Default: ''

Examples

0

#1 Get all post attachment files

$attaches = get_children( [
	'post_type' => 'attachment',
	'post_parent' => 25,
] );

/* $attaches will contain:
Array (
	[7144] => WP_Post Object
		(
			[ID] => 7144
			[post_author] => 1
			[post_date] => 2016-06-19 07:47:55
			[post_date_gmt] => 2016-06-19 02:47:55
			[post_content] =>
			[post_title] => democracy-ico
			[post_excerpt] =>
			[post_status] => inherit
			[comment_status] => open
			[ping_status] => closed
			[post_password] =>
			[post_name] => democracy-ico
			[to_ping] =>
			[pinged] =>
			[post_modified] => 2016-06-19 07:47:55
			[post_modified_gmt] => 2016-06-19 02:47:55
			[post_content_filtered] =>
			[post_parent] => 67
			[guid] => /wp-content/uploads/2010/06/democracy-ico.png
			[menu_order] => 0
			[post_type] => attachment
			[post_mime_type] => image/png
			[comment_count] => 0
			[filter] => raw
		)

	[5576] => WP_Post Object
		(
		...
*/
0

#2 Gets post attachments by type

If we need to retrieve attachments and process them, we use the following code:

$images = get_children( 'post_type=attachment&post_mime_type=image' );
$videos = get_children( 'post_type=attachment&post_mime_type=video/mp4' );

if( ! $images ) {
	// no attaches
}
else {
	foreach ( $images as $attachment_id => $attachment ) {
		echo wp_get_attachment_image( $attachment_id, 'full' );
	}
}

OR if there is no need to handle an empty result:

foreach ( (array) $videos as $attachment_id => $attachment ) {
	echo wp_get_attachment_link( $attachment_id );
}
0

#3 Get and output all the images associated with the post 740

$attachments = get_children( array(
	'post_parent'    => 740,
	'order'          => 'ASC',
	'post_mime_type' => 'image',
	'post_type'      => 'attachment',
) );

if( $attachments ){
	foreach( $attachments as $attachment ){
		$image_src = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' )[0]
			 ?: wp_get_attachment_image_src( $attachment->ID, 'full' )[0];

		$image_desc = $attachment->post_content ?: $attachment->post_title;

		echo '<img src="'. $image_src .'" alt="'. esc_attr( $image_desc ) .'" class="current">';
	}
}
else
	echo 'No attachments';
0

#4 Show the first image associated with the post

In the example below, the indexes of the main array contains the image (post) IDs (but if we don't know the ID, how can we access the first image? - this may be inconvenient). The code below shows how to directly access the image information from the $child_image array.

$args = [
	'numberposts' => 1,
	'order'=> 'DESC',
	'post_mime_type' => 'image',
	'post_parent' => $post->ID,
	'post_type' => 'attachment'
];

$children = get_children( $args );  // returns an array with keys: [ $image_ID ]
$first_image = reset( $children ); // get first element

print_r( $first_image );  // Let's display the data array on the screen.
echo $first_image->ID;    // gets the image ID
0

#5 Wildcard in the post_mime_type parameter

This example shows how to use the wildcard % in the value of 'post_mime_type' parameter. It works as % sign in SQL LIKE query (a combination of any characters).

$children = get_children( [
	'post_parent'    => $post->ID,
	'post_status'    => 'inherit',
	'post_type'      => 'attachment',
	'post_mime_type' => 'audio/%'
] );
0

#6 The navigation block for hierarchical post

The navigation displays all posts on the same level and first level child posts.

/**
 * The navigation block for hierarchical post.
 *
 * The navigation displays all posts on the same level and first level child posts.
 *
 * @return string HTML code of links block.
 */
function handbook_nav_block() {

	if( ! is_singular('handbook') )
		return;

	global $post;

	// collect all IDs
	$include = [ $post->ID ];

	// parents
	$include = array_merge( $include, $post->ancestors );

	$arr = [
		'post_type'   => $post->post_type,
		//'post_status' => 'any',
		//'orderby'     => 'menu_order',
		//'order'       => 'ASC',
	];

	// adjacent
	$siblings = get_children( $arr + ['post_parent' => $post->post_parent] );
	foreach( (array) $siblings as $pst ){
		$include[] = $pst->ID;

		// The child pages of all posts on the same level as the current one (only if it is not the top level).
		/*
		if( $pst->post_parent !== 0 ){
			if( $subchilds = get_children( $arr + ['post_parent' => $pst->ID] ) )
				foreach( (array) $subchilds as $pst ) $include[] = $pst->ID;
		}
		*/
	}

	// collect all children
	$childs = get_children( $arr + ['post_parent' => $post->ID] );
	foreach( (array) $childs as $pst ){
		$include[] = $pst->ID;
	}

	$children = wp_list_pages([ 'include'=>$include, 'post_type'=>'handbook', 'title_li'=>'', 'echo'=>0 ]);

	return '
	<style>
		.handbook__nav{ background: #eee; padding: .8em 2.5rem; margin: 2em -2.5rem; }
		.handbook__nav .title{ margin:.3em 0 .7em; }
		.handbook__nav .current_page_item > a{ font-weight:bold; }
		.handbook__nav ul ul{ margin-left:0; }
		.handbook__nav ul.children{ margin-top:.5em; }
	</style>

	<div class="handbook__nav">
		<h3 class="title">Navigation</h3>
		<ul>
			'. $children .'
		</ul>
	</div>';

}

Notes

  • See: get_posts()
  • Global. WP_Post. $post Global post object.

Changelog

Since 2.0.0 Introduced.

get_children() code WP 6.5.2

function get_children( $args = '', $output = OBJECT ) {
	$kids = array();
	if ( empty( $args ) ) {
		if ( isset( $GLOBALS['post'] ) ) {
			$args = array( 'post_parent' => (int) $GLOBALS['post']->post_parent );
		} else {
			return $kids;
		}
	} elseif ( is_object( $args ) ) {
		$args = array( 'post_parent' => (int) $args->post_parent );
	} elseif ( is_numeric( $args ) ) {
		$args = array( 'post_parent' => (int) $args );
	}

	$defaults = array(
		'numberposts' => -1,
		'post_type'   => 'any',
		'post_status' => 'any',
		'post_parent' => 0,
	);

	$parsed_args = wp_parse_args( $args, $defaults );

	$children = get_posts( $parsed_args );

	if ( ! $children ) {
		return $kids;
	}

	if ( ! empty( $parsed_args['fields'] ) ) {
		return $children;
	}

	update_post_cache( $children );

	foreach ( $children as $key => $child ) {
		$kids[ $child->ID ] = $children[ $key ];
	}

	if ( OBJECT === $output ) {
		return $kids;
	} elseif ( ARRAY_A === $output ) {
		$weeuns = array();
		foreach ( (array) $kids as $kid ) {
			$weeuns[ $kid->ID ] = get_object_vars( $kids[ $kid->ID ] );
		}
		return $weeuns;
	} elseif ( ARRAY_N === $output ) {
		$babes = array();
		foreach ( (array) $kids as $kid ) {
			$babes[ $kid->ID ] = array_values( get_object_vars( $kids[ $kid->ID ] ) );
		}
		return $babes;
	} else {
		return $kids;
	}
}