WordPress获取文章子元素函数:get_children

2022/07/13

WordPress函数get_children可用于获取文章下的附件、子页面,通常我用来获取文章缩略图。

get_children( array $args = '', constant $output = OBJECT )

函数参数

$args

数组或字符串值

get_children()函数$args参数默认的值如下:

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

get_children()函数$args参数可用的值如下:

numberposts

整数型,默认值:-1

指定返回信息的数量,默认不限制

post_parent

整数型,默认值:0

父元素的ID,指定一个文章ID,将返回该文章下的子元素

post_type

字符串值,默认值:any

指定文章类型,例如:attachment、page、revision,默认所有类型

post_status

字符串值,默认值:any

文章状态,例如:publish、draft、inherit

post_mime_type

字符串值,默认为空

指定文件的MIME类型,例如:image、video、video/mp4,在返回指定格式的附件时特别有用

函数返回值

Array (
	[240] => WP_Post Object (
	[ID] => 240
	[post_author] => 1
	[post_date] => 2014-07-25 09:27:19
	[post_date_gmt] => 2014-07-25 01:27:19
	[post_content] =>
	[post_title] => baiduseo
	[post_excerpt] =>
	[post_status] => inherit
	[comment_status] => open
	[ping_status] => closed
	[post_password] =>
	[post_name] => baiduseo
	[to_ping] =>
	[pinged] =>
	[post_modified] => 2014-07-25 09:27:19
	[post_modified_gmt] => 2014-07-25 01:27:19
	[post_content_filtered] =>
	[post_parent] => 239
	[guid] => http://localhost/wp-content/uploads/2014/07/baiduseo.jpg
	[menu_order] => 0
	[post_type] => attachment
	[post_mime_type] => image/jpeg
	[comment_count] => 0
	[filter] => raw )
)

函数使用示例

返回ID为239的文章下的所有图片:

$images = get_children( 'post_parent=239&post_type=attachment&post_mime_type=image' );

获取文章第一张图片的缩略图:

<?php
function echo_first_image( $postID ) {
	$args = array(
		'numberposts' => 1,
		'order' => 'ASC',
		'post_mime_type' => 'image',
		'post_parent' => $postID,
		'post_status' => null,
		'post_type' => 'attachment',
	);
	$attachments = get_children( $args );
	if ( $attachments ) {
		foreach ( $attachments as $attachment ) {
			echo '<img src="' . wp_get_attachment_thumb_url( $attachment->ID ) . '" class="current">';
		}
	}
}
?>

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注