从子页面调用和显示附件 - WordPress

问题描述 投票:0回答:1

我是WordPress(duh)的新手并尝试了一些我非常接近的东西。

我有几个子页面,每个子页面都有附件 - 图像。我只是想显示这些图像。客户端将定期添加更多子页面,因此代码必须知道只显示其自身的图像,可以这么说。我遇到的一个问题是每个子页面都显示所有子页面的所有附件。

在我的Functions.php中,我有这个代码来确定页面是否实际上是一个子页面:

//find out if it is a suppage to use in page.php as function 'is_subpage'
function is_subpage() {
    global $post;                              // load details about this page

    if ( is_page() && $post->post_parent ) {   // test to see if the page has a parent
        return $post->post_parent;             // return the ID of the parent post

    } else {                                   // there is no parent so ...
        return false;                          // ... the answer to the question is false
    }
}

在我的page.php中,我有一个If语句,用于我所有的常用页面。它达到了高潮:

    elseif ( is_subpage() ) {
      get_template_part( 'exhibition-template' );
      get_template_part( 'normalfooter' );
    }

exhibition-template.php,我希望我的图像出现在哪里,我有这个:

<?php

if ( is_subpage( $post->ID ) ) { //I think I screwed up here, innermost brackets


$args = array(
    'order'          => 'ASC',
    'post_type'      => 'attachment',
    'post_parent'    => $post->ID, //or is my issue here...?
    'post_mime_type' => 'image',
    'post_status'    => null,
    'numberposts'    => -1,
);
$attachments = get_posts($args);
    if ($attachments) {
        foreach ($attachments as $attachment) {
            echo wp_get_attachment_link($attachment->ID, 'large', false, false);
        }
    }
}    
?>

但是,所发生的事情是每个子页面都只显示所有子页面中的所有图像,坦率地说,我只是想知道如何进步,或者要玩什么,从哪里开始。有任何想法吗?

php wordpress image if-statement attachment
1个回答
0
投票

看起来你有一些问题。

在测试页面是否是子页面时,您应该测试以查看$post->post_parent是否大于0.所以像这样:

if ( is_page() && $post->post_parent > 0 ) {
    return $post->post_parent;
} else {
    return false;
}

你不需要将任何参数传递给if ( is_subpage( $post->ID ) )..。您也可以使用WordPress的get_attached_media()函数来获取这些附件。这就是你的exhibition-template.php看起来的样子:

if ( is_subpage() ) {

    $attachments = get_attached_media('image', $post->ID);

    foreach ($attachments as $attachment) {
        echo wp_get_attachment_link($attachment->ID, 'large', false, false);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.