WordPress获取文章子元素函数:get_children
文 / @WordPress主题
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">'; } } } ?>
扩展阅读
get_children()函数位于:wp-includes/post.php
相关函数:
- wp_get_attachment_link()
- get_page_children()

相关文章
-
搭建一个WordPress网站需要多少成本 2023-11-06 00:09:51
-
Symlink介绍(附:如何使用Symlink进行WordPress开发) 2023-11-05 23:38:32
-
让WordPress实现数据库同步的插件:HyperDB 2023-10-24 23:40:49
-
allegro电商平台值得做吗(附:2023年Allegro注册流程指南) 2023-10-08 21:53:39
-
印度跨境电商平台有哪些(附:印度跨境电商做什么产品好) 2023-10-08 21:34:23
-
跨境电商必看的几大海外二手电商平台 2023-10-08 18:04:42
-
WordPress同城互联网产品解决方案:UBASE 2023-10-03 16:40:39
-
WordPress网站的安全插件:wordfence 2023-09-14 09:25:18
-
WordPress 6.3 支持在手动更新插件和主题失败后回滚旧版本 2023-08-28 16:58:45
-
WordPress 6.3版本(2023年8月)性能提升了哪些? 2023-08-28 16:56:02