概要
get_children
関数は、指定した投稿の子投稿を取得するための WordPress 関数です。この関数は、主に以下のような機能を実装する際によく使われます。
- 投稿情報の付加投稿情報を取得する
- 特定のページやカスタム投稿タイプの子投稿のリストを表示する
- 画像やメディアのギャラリーを作成する
- 特定の条件に基づいて投稿をフィルタリングする
- 投稿の階層構造に基づくナビゲーションメニューを作成する
- 親投稿に紐づく子投稿を表示する
- コンタクトフォームなどの子要素を管理する
- 特定のカテゴリやタグに基づくコンテンツの表示
構文
get_children( $args );
パラメータ
$args
(配列) – チルド投稿を取得するためのクエリ引数。post_parent
(整数) – 親投稿の ID。post_type
(文字列) – 投稿タイプ(デフォルトは ‘any’)。post_status
(文字列) – 投稿の公開状態(デフォルトは ‘publish’)。numberposts
(整数) – 取得する投稿の数(デフォルトは -1 として全投稿を取得)。
戻り値
get_children
は、指定した条件にマッチする子投稿の配列を返します。条件に合致する子投稿が存在しない場合は、空の配列を返します。
関連する関数
使用可能なバージョン
この関数は、WordPress バージョン 1.5.0 以降で利用可能です。
コアファイルのパス
wp-includes/post.php
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | 〇 |
wp | 〇 |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプル1: 子投稿の取得
$children = get_children( array(
'post_parent' => 123,
'post_type' => 'post',
'numberposts' => -1
) );
foreach ( $children as $child ) {
echo '<li>' . $child->post_title . '</li>';
}
このサンプルコードは、IDが 123
の親投稿に紐づくすべての子投稿を取得し、それらのタイトルをリストとして表示します。
サンプル2: 特定の投稿タイプの子投稿を取得
$children = get_children( array(
'post_parent' => 456,
'post_type' => 'page',
'post_status' => 'publish'
) );
if ( !empty( $children ) ) {
foreach ( $children as $child ) {
echo '<h2>' . $child->post_title . '</h2>';
}
}
このサンプルは、IDが 456
の親ページから、公開された子ページを取得し、それらのタイトルを見出しとして表示しています。
サンプル3: 除外投稿の取得
$children = get_children( array(
'post_parent' => 789,
'post_type' => 'attachment',
'exclude' => array(111, 112)
) );
foreach ( $children as $child ) {
echo '<img src="' . wp_get_attachment_url($child->ID) . '" />';
}
このサンプルでは、IDが 789
の親投稿に関連する添付ファイルを取得し、特定のIDを持つ投稿を除外して、画像を表示しています。
サンプル4: 特定の数の子投稿を取得
$children = get_children( array(
'post_parent' => 321,
'numberposts' => 5
) );
foreach ( $children as $child ) {
echo '<p>' . $child->post_title . '</p>';
}
このコードは、IDが 321
の親投稿の子投稿の中から最新の5件を取得し、それらのタイトルを段落として表示します。
サンプル5: 親投稿詳細の表示
$parent_id = 654;
$children = get_children( array( 'post_parent' => $parent_id ) );
if ( count( $children ) > 0 ) {
echo '<h3>子投稿一覧</h3><ul>';
foreach ( $children as $child ) {
echo '<li>' . $child->post_title . '</li>';
}
echo '</ul>';
} else {
echo '子投稿はありません。';
}
このサンプルは、IDが 654
の親投稿が持つ子投稿を取得し、子投稿が存在する場合はそのリストを表示し、存在しない場合はその旨を表示します。