【问题标题】:How to retrieve attachments from child pages of a specific Page in WordPress?如何从 WordPress 中特定页面的子页面中检索附件?
【发布时间】:2012-06-15 18:06:48
【问题描述】:

如何从特定页面 ID 的所有子页面中检索附件?

例子:

特定页面

  • 孩子(带附件)
  • 孩子(带附件)
  • 孩子(带附件)

我目前正在使用此代码来检索站点范围内的所有附件,但是我想将其限制为仅从特定页面的所有子项中提取图像。

<?php
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => null ); 
$attachments = get_posts( $args );
if ($attachments) {
    foreach ( $attachments as $post ) {
        setup_postdata($post);
        the_title();
        the_attachment_link($post->ID, false);
        the_excerpt();
    }
}
?>

按照尼克的建议,几乎可以使用此代码:

<?php

$mypages = get_pages('child_of=19');
foreach ( $mypages as $mypage  ) {
$attachments = get_children(array('post_parent' => $mypage->ID, 'numberposts' => 1, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'rand'));


if ($attachments) {

    foreach ( $attachments as $post ) {

        setup_postdata($post);
        the_title();
        the_attachment_link($post->ID, false);
        the_excerpt();
    }
}
}
?>

但是,还有两个问题:

  1. 限制提取的照片总数。使用“numberposts”只会限制从每个帖子中提取的图片数量
  2. 随机化。 Orderby => rand 仅随机化每个帖子中的图像。我想随机打乱所有东西的顺序。

【问题讨论】:

标签: php html wordpress


【解决方案1】:

尝试使用get_pages( $args )

<?php $args = array(
'child_of' => 'SPECIFIC PAGE',
'parent' => 'SPECIFIC PAGE',
'post_type' => 'attachment',
'post_status' => 'publish',
'numberposts' => -1
); ?>

使用child_of 将得到所有子孙。

parent 会将其限制为仅将其作为父级的子级。没有孙子。

请参阅此处了解更多详情。 http://codex.wordpress.org/Function_Reference/get_pages

【讨论】:

  • @Joe,您可以将所有附件数据存储在一个多维数组中并shuffle 它。然后使用for 循环显示正确数量的附件。
  • 只是好奇-这不会仍然提取额外的未使用数据(例如,有 1,000 张图像)吗?我认为这是为服务器完成了很多浪费的工作?
  • 您已经在get_children() 调用中从数据库中提取了数据。现在您只需要对其进行操作。与其在 foreach 循环中输出,不如将其存储在数组中。然后打乱数组,然后循环遍历数组以输出你想要的。是的,还有一点工作要做,但我想不出一种方法可以从 get_children()get_pages() 调用中得到你想要的。
猜你喜欢
  • 2019-05-23
  • 2014-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
相关资源
最近更新 更多