您的当前位置:首页 > 知识博客 > wordpress建站

get_children 根据父级文章信息文章的附件、版本、或子页面

时间:2024-04-02

函数描述

get_children()函数根据父级文章信息获取文章的附件、版本或子页面,与get_posts()函数类似。

使用方法

<?php $children_array = get_children($args, $output); ?>

默认使用方法

$args = [     'post_parent' => 0,     'post_type' => 'any',     'numberposts' => -1,     'post_status' => 'any', ];

参数

可用于$args数组的选项包括:

  • ‘numberposts’ (integer) (可选):需要获取的文章数量。默认:‘-1’

  • ‘post_parent’ (integer) (可选):传递文章或页面的ID以获取子内容,传递0获取没有父级的附件,传递null获取父级页面。默认:‘0’

  • ‘post_type’ (string) (可选):wp_posts数据表中的post_type列的任意值,如attachment,page或revision;或者关键字any获取所有文章类型。默认:‘0’

  • ‘post_status’ (string) (可选):wp_posts数据表中post_status列的任意值,如publish,draft或inherit;或关键字any获取所有文章状态。默认:‘any’

  • ‘post_mime_type’ (string) (可选):全不或部分mime-type,如:image,video,video/mp4,和文章的post_mime_type字段相对应。默认:None

注意:查看get_posts()以$args参数的全部列表。‘output’(constant) (可选):函数返回的数组类型:OBJECT、ARRAY_A或ARRAY_N中的一个。默认:OBJECT

在2.6版本中,必须传递一个非空的post_type参数(attachment或page)。

返回值

(array):以文章ID作为数组key的关联文章数组($output参数设置的变量类型),获取失败返回空数组。

注意: 在2.9版本以前,如果没有找到子文章,则返回false。

使用示例

如果只想显示附件,使用get_posts()代替可能会更容易一些。

$images = get_children('post_type=attachment&post_mime_type=image'); $videos = get_children('post_type=attachment&post_mime_type=video/mp4'); if (empty($images)) {     //没有图片 } else {     foreach ($images as $attachment_id => $attachment) {         echo wp_get_attachment_image($attachment_id, 'full');     } } // 如果不需要处理空结果 I: foreach ((array)$videos as $attachment_id => $attachment) {     echo wp_get_attachment_link($attachment_id); }

显示关联到文章的第一张图片

下面的函数获取关联到文章的第一张图片。

function echo_first_image($postID) {     $args = [         '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) {             $image_attributes = wp_get_attachment_image_src($attachment->ID, 'thumbnail') ? wp_get_attachment_image_src($attachment->ID, 'thumbnail') : wp_get_attachment_image_src($attachment->ID, 'full');             echo '<img src="' . wp_get_attachment_thumb_url($attachment->ID) . '">';         }     } }

显示关联到文章的第一张图片并且重新排列数组

在上面的示例中,主数组的键位图片ID,(确切的东西,被我们不知道我们怎么访问它?)。下面的代码提供了一个更方便的处理图片信息的方法:数组$child_image,应该在文章循环中使用。

$args = [     'numberposts' => 1,     'order' => 'DESC',     'post_mime_type' => 'image',     'post_parent' => $post->ID,     'post_type' => 'attachment', ]; $get_children_array = get_children($args, ARRAY_A);//返回数组([$image_ID]... $rekeyed_array = array_values($get_children_array); $child_image = $rekeyed_array[0]; print_r($child_image);//打印$child_image数组的内容


欢迎咨询/Welcome to inquire
tel/vx:18842938855
qq:1685522781
email:1685522781@qq.com

Copyright © 2019-2024 baidu.bond


Whatsapp
Powered by RRZCMS