get_children()
概述
get_children() 函数用于检索指定文章父ID的所有子文章,通常应用于页面、文章和附件等共享数据库表的场景。它基于 get_posts() 函数实现,允许通过参数自定义查询条件,如文章类型、状态和返回格式。
关键要点
- 核心功能:检索文章父ID的子文章,默认适用于页面,但也可用于其他文章类型如附件。
- 参数处理:$args 参数可接受对象、整数或数组,用于指定 post_parent 和其他查询条件;$output 参数控制返回类型(OBJECT、ARRAY_A 或 ARRAY_N)。
- 默认行为:若无参数,函数从全局 $post 中获取父ID;默认检索所有文章(numberposts 为 -1),文章类型和状态为 'any'。
- 依赖关系:内部调用 get_posts() 函数,参数通过 wp_parse_args() 合并默认值,支持 get_posts() 的额外参数。
- 返回结果:根据 $output 返回 WP_Post 对象数组、关联数组或数字数组,子文章以 ID 为键缓存。
代码示例
// 示例:检索文章的所有图像附件
$args = array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => -1,
'order' => 'ASC'
);
$attachments = get_children( $args, ARRAY_A );注意事项
- 函数不直接适用于文章(posts),但可通过参数调整实现;附件自 WordPress 2.5 后可能已变化,使用时需验证。
- 检索图像时,注意附件必须是目标文章的子项,重用其他文章的附件可能导致无结果。
- 参数传递需谨慎:若 $args 为对象或整数,仅提取 post_parent,其他参数丢失;建议使用数组形式。
Retrieves all children of the post parent ID.
Description
Normally, without any enhancements, the children would apply to pages. In the context of the inner workings of WordPress, pages, posts, and attachments share the same table, so therefore the functionality could apply to any one of them. It is then noted that while this function does not work on posts, it does not mean that it won’t work on posts. It is recommended that you know what context you wish to retrieve the children of.
Attachments may also be made the child of a post, so if that is an accurate statement (which needs to be verified), it would then be possible to get all of the attachments for a post. Attachments have since changed since version 2.5, so this is most likely inaccurate, but serves generally as an example of what is possible.
The arguments listed as defaults are for this function and also of the get_posts() function. The arguments are combined with the get_children defaults and are then passed to the get_posts() function, which accepts additional arguments.
You can replace the defaults in this function, listed below and the additional arguments listed in the get_posts() function.
The ‘post_parent’ is the most important argument and important attention needs to be paid to the $args parameter. If you pass either an object or an integer (number), then just the ‘post_parent’ is grabbed and everything else is lost. If you don’t specify any arguments, then it is assumed that you are in The Loop and the post parent will be grabbed for from the current post.
The ‘post_parent’ argument is the ID to get the children. The ‘numberposts’ is the amount of posts to retrieve that has a default of ‘-1’, which is used to get all of the posts. Giving a number higher than 0 will only retrieve that amount of posts.
The ‘post_type’ and ‘post_status’ arguments can be used to choose what criteria of posts to retrieve. The ‘post_type’ can be anything, but WordPress post types are ‘post’, ‘pages’, and ‘attachments’. The ‘post_status’ argument will accept any post status within the write administration panels.
See also
Parameters
$argsmixedoptional-
User defined arguments for replacing the defaults. Default empty.
$outputstringoptional-
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
Source
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;
}
}
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
Skip to note 8 content
farfromunique
Each item returned by
get_children()has the following values (names shown are mapped fromARRAY_A; same names are used withOBJECT):array(24) {<br />["ID"] => (int)<br />
["post_author"] => (string)<br />
["post_date"] => (string)<br />
["post_date_gmt"] => (string)<br />
["post_content"] => (string)<br />
["post_title"] => (string)<br />
["post_excerpt"] => (string)<br />
["post_status"] => (string)<br />
["comment_status"] => (string)<br />
["ping_status"] => (string)<br />
["post_password"] => (string)<br />
["post_name"] => (string)<br />
["to_ping"] => (string)<br />
["pinged"] => (string)<br />
["post_modified"] => (string)<br />
["post_modified_gmt"] => (string)<br />
["post_content_filtered"] => (string)<br />
["post_parent"] => (int)<br />
["guid"] => (string)<br />
["menu_order"] => (int)<br />
["post_type"] => (string)<br />
["post_mime_type"] => (string)<br />
["comment_count"] => (string)<br />
["filter"] => (string)<br />
}
Skip to note 9 content
Codex
Show the first image associated with the post
This function retrieves the first image associated with a post
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 ) { $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' ); echo '<img src="' . esc_url( wp_get_attachment_thumb_url( $attachment->ID ) ) . '" class="current" />'; } } }Skip to note 10 content
Codex
Show the first image associated with the post and re-key the array
In the example above, a primary array is keyed with the image ID (the exact thing which is being sought – since we don’t know it how are we supposed to access it?). The code below provides an easier handle for the image information: the array $child_image. Should be used in the loop.
$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 ); //returns Array ( [$image_ID]. $rekeyed_array = array_values( $get_children_array ); $child_image = $rekeyed_array[0]; print_r( $child_image ); //Show the contents of the $child_image array. echo $child_image['ID']; //Show the $child_image ID.Skip to note 11 content
samjco
Get ALL Parent Posts IDs
$post_type ="post"; //page, or custom_post_type $post_status = "any"; //publish, draft, etc $num_of_posts = -1; // -1 for all, or amount # to return $post_parent = 0; //0 for parents, or and id $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; }Skip to note 12 content
Anonymous User
This is not safe for extracting the first image from posts!
As the name given, this function actually returns the children from a parent objects. Which means if you reuse an image for a new post, it won’t return the image. For instance:
First, make a new post A and upload these images A01.jpg, A02.jpg and A03.jpg to the post A. Then those images, aka. Attachments, (A01, A02, A03) are children of post A. With this, we can retrieve image A01 from post A in the loop. It is a common way to replace thumbnail in case writers forgets to add thumbnail. But! What if we make a second post?
Let make a second post B and reuse the uploaded images (A01 and A02) from post A. In this case, no image will be returned from the
get_childrenbecause images A01 and A02 are not post B’s children. This means if the design of our theme will be broken for sure because there is no image to display on the posts in the index page. Unless the theme is designed for specific case with careful guide for users, this function should not be used for retrieving image from posts!<?php function print_first_kid_image_of_post($post_id) { $arr = array( 'posts_per_page' => 1, # This param ensures only 1 post returned in the array 'post_mime_type' => 'image', 'post_parent' => $post_id, 'post_type' => 'attachment', ); $imgs = get_children($arr); # Return an array with an item $img = $imgs[0]; $img_id = $img->ID; $img_size = 'thumbnail' echo wp_get_attachment_image($img_id, $img_size); }Result:- Post A (uploaded images: A1, A2, A3): image A1
- Post B (reused images: A1, A2): NULL
- Post C (reused images: A1) (uploaded images: C1, C2, C3): image C1 (even if image A1 is placed on top, image C1 is still returned because A1 is not a child of Post C)
Skip to note 13 content
Koen Reus
To get an array of child IDs only, pass ‘fields’ => ‘ids’ in the function args array.
get_children( [ 'post_parent' => $post_id, 'fields' => 'ids', ] );Skip to note 14 content
Codex
Example
If you just want to get or display attachments, it’s probably a little easier to use get_posts() instead.
$images =& get_children( array( 'post_type' => 'attachment', 'post_mime_type' => 'image' ); $videos =& get_children( array( 'post_type' => 'attachment', 'post_mime_type' => 'video/mp4' ); if ( empty( $images ) ) { // no attachments here } else { foreach ( $images as $attachment_id => $attachment ) { echo wp_get_attachment_image( $attachment_id, 'full' ); } } // If you don't need to handle an empty result: foreach ( (array) $videos as $attachment_id => $attachment ) { echo wp_get_attachment_link( $attachment_id ); }