个性化阅读
专注于IT技术分析

WordPress:显示特定页面的子页面中的图像附件

点击下载

我正在尝试在特定父页面的子页面上显示所有图像附件, 即页面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' );
        }
    }

?>

任何建议将非常有帮助!


#1


我认为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' );
        }
    }

}
?>

祝好运 :)


#2


这是一个基于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');
}
赞(0)
未经允许不得转载:srcmini » WordPress:显示特定页面的子页面中的图像附件

评论 抢沙发

评论前必须登录!