我正在尝试在特定父页面的子页面上显示所有图像附件,即页面10、11和12上的所有图片。
Projects (Page ID: 5)
- Project 1 (Page ID: 10)
- Project 2 (Page ID: 11)
- Project 3 (Page ID: 12)
这是我到目前为止的内容,它可以显示网站上的所有图像:
<?php
$args = array(
'post_parent' => 0,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
?>
但是,如果我添加帖子的父ID(5),则什么也没有出现:
<?php
$args = array(
'post_parent' => 5,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
?>
任何建议都会很有帮助!
答案 0 :(得分:0)
我认为get_children()从单个父帖子或全部父帖子中返回对象(将值传递0)。
您可以尝试使用嵌套的foreach首先获取所有帖子子级,然后逐页查询附件。这是一个未经测试的示例,但它为您提供了一个思路:
<?php
$subpages_args = array(
'post_parent' => 5,
'post_type' => 'page',
'numberposts' => -1
);
$sub_pages = get_children( $subpages_args );
foreach( $sub_pages as $subpage_id => $sub_page) {
$args = array(
'post_parent' => subpage_id,
'post_type' => 'attachment',
'numberposts' => -1
);
$images = get_children( $args );
if ( empty($images) ) {
// no attachments here
} else {
foreach ( $images as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, 'full' );
}
}
}
?>
祝你好运:)
答案 1 :(得分:0)
这是基于SQL查询的解决方案。在主题的functions.php中复制以下函数
function get_children_page_attachments($parent_id) {
global $wpdb;
// just a precautionary typecast and check
$parent_id = intval( $parent_id );
if( empty($parent_id) ) return [];
$query = "SELECT ID FROM {$wpdb->posts} P WHERE post_type='attachment' AND P.post_parent IN (SELECT ID FROM {$wpdb->posts} WHERE post_parent={$parent_id} AND post_type='page' )";
return $wpdb->get_results($query, 'ARRAY_A');
}
一旦您在functions.php中具有上述功能,就可以像这样使用它:
// for example the parent page id is 16
$image_ids = get_children_page_attachments(16);
foreach($image_ids as $image_id) {
$image = wp_get_attachment_image($image_id['ID'], 'full');
}