## Функция GET_CHILDREN() │ WP 2.0.0
Функция get_children() позволяет получить всех потомков (вложения, версии или подстраницы) для заданного поста. Это похоже на функцию get_posts().
### Применение
- Используется в: get_attached_media(), wp_get_post_revisions(), wp_playlist_shortcode()
**Нет хуков.**
### Возвращаемое значение
Функция возвращает массив объектов постов, массивов или идентификаторов (ID) в зависимости от значения $output.
## Шаблон использования
```php
$childrens = get_children( [
'post_parent' => 0,
'post_type' => 'any',
'numberposts' => -1,
'post_status' => 'any'
] );
if( $childrens ){
foreach( $childrens as $children ){
// вывод информации
}
}
Использование
get_children( $args, $output );
Параметры $args
Для полной информации о параметрах $args смотрите в документации к get_posts().
Кроме этого списка параметров, вы можете использовать любые параметры из WP_Query.
numberposts(int) — количество дочерних постов для получения.-1означает всех.post_parent(int) — ID поста, для которого нужно получить детей. Используйте0для получения вложений без родителя иnullдля получения любых детей, независимо от родителя.post_type(string) — тип поста (например,attachment,page,revisionилиany).post_status(string) — статус поста (например,publish,draft,inheritилиany).post_mime_type(string) — полный или частичный mime-type (например,image,video,audio), который сопоставляется с полемpost_mime_typeпоста.
Примеры использования
Пример 1: Получение всех файлов вложений поста
$attaches = get_children( [
'post_type' => 'attachment',
'post_parent' => 25,
] );
/* $attaches будет содержать:
Array (
[7144] => WP_Post Object
(
[ID] => 7144
[post_author] => 1
...
[post_type] => attachment
...
)
...
)
Пример 2: Получение вложений по типу
$images = get_children( 'post_type=attachment&post_mime_type=image' );
$videos = get_children( 'post_type=attachment&post_mime_type=video/mp4' );
if( ! $images ) {
// нет вложений
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
Пример 3: Получение и вывод всех изображений, связанных с постом 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 '
';
}
} else {
echo 'Нет вложений';
}
Пример 4: Отображение первого изображения, связанного с постом
$args = [
'numberposts' => 1,
'order'=> 'DESC',
'post_mime_type' => 'image',
'post_parent' => $post->ID,
'post_type' => 'attachment'
];
$children = get_children( $args ); // возвращает массив с ключами: [ $image_ID ]
$first_image = reset( $children ); // получить первый элемент
print_r( $first_image ); // Вывод данных на экран.
echo $first_image->ID; // Получить ID изображения
Пример 5: Идентификатор с подстановочным знаком в параметре post_mime_type
$children = get_children( [
'post_parent' => $post->ID,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'audio/%'
] );
Пример 6: Навигационный блок для иерархического поста
function handbook_nav_block() {
if( ! is_singular('handbook') )
return;
global $post;
// собираем все ID
$include = [ $post->ID ];
$include = array_merge( $include, $post->ancestors );
$arr = [
'post_type' => $post->post_type,
];
$siblings = get_children( $arr + ['post_parent' => $post->post_parent] );
foreach( (array) $siblings as $pst ){
$include[] = $pst->ID;
}
$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 '
Навигация
'. $children .'
';
}
Заметки
- Глобальная переменная:
WP_Post $post— глобальный объект поста.
Журнал изменений
- С версии 2.0.0 — внедрена.