get_page_children()通过页面id获取所有子页面

目录

描述

译文

在编号相匹配的页面列表中检索子页面。

要与页面编号上的页面参数相匹配。还需要与子页面相匹配,以便检索某一页面上的所有子页面。切勿使用SQL查询来获取子页面。

原文

Retrieve child pages from list of pages matching page ID.

Matches against the pages parameter against the page ID. Also matches all children for the same to retrieve all children of a page. Does not make any SQL queries to get the children.

get_page_children() 描述

用法

<?php &get_page_children$page_id$pages ?>
<?php get_page_children
$page_id$pages ?>

get_page_children() 用法

参数

$page_id

(integer) (必填) Page ID.

默认值: None

$pages

(array) (必填) List of pages' objects.

默认值: None

get_page_children() 参数

返回值

(array) 

get_page_children() 返回值

示例

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
<?php
// Set up the objects needed
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));

// Get the page as an Object
$portfolio =  get_page_by_title('Portfolio');

// Filter through all pages and find Portfolio's children
$portfolio_children = get_page_children( $portfolio->ID, $all_wp_pages );

// echo what we get back from WP to the browser
echo '<pre>' . print_r( $portfolio_children, true ) . '</pre>';
?>

get_page_children() 示例

注意

This function calls itself recursively.

get_page_children() 注意

历史

添加于 版本: 1.5.1

get_page_children() 历史

源文件

&get_page_children() 函数的代码位于 wp-includes/post.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Identify descendants of a given page ID in a list of page objects.
 *
 * Descendants are identified from the `$pages` array passed to the function. No database queries are performed.
 *
 * @since 1.5.1
 *
 * @param int   $page_id Page ID.
 * @param array $pages   List of page objects from which descendants should be identified.
 * @return array List of page children.
 */
function get_page_children( $page_id, $pages ) {
	// Build a hash of ID -> children.
	$children = array();
	foreach ( (array) $pages as $page ) {
		$children[ intval( $page->post_parent ) ][] = $page;
	}

	$page_list = array();

	// Start the search by looking at immediate children.
	if ( isset( $children[ $page_id ] ) ) {
		// Always start at the end of the stack in order to preserve original `$pages` order.
		$to_look = array_reverse( $children[ $page_id ] );

		while ( $to_look ) {
			$p = array_pop( $to_look );
			$page_list[] = $p;
			if ( isset( $children[ $p->ID ] ) ) {
				foreach ( array_reverse( $children[ $p->ID ] ) as $child ) {
					// Append to the `$to_look` stack to descend the tree.
					$to_look[] = $child;
				}
			}
		}
	}

	return $page_list;
}

get_page_children() 源文件

相关