問題描述

我在這個示例小工具代碼中遇到麻煩。我想從一個名為”Gallery” 的頁面中獲取所有圖像 (縮小後的縮略圖),但由於某種原因,這是從整個站點拉出所有上傳的圖像。

另外,如何從此查詢中排除帖子縮略圖?

  query_posts('pagename=gallery');
if (have_posts()) :
echo "<ul class='recentwidget group photowidget'>";
while (have_posts()) : the_post();
    $args = array(
    'post_type' => 'attachment',
    'numberposts' => 1,
    'post_status' => null,
    'post_parent' => $post->ID
);

$attachments = get_posts( $args );
    if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
       echo '<li class="left imageshadow photolarge">';
       echo wp_get_attachment_image( $attachment->ID, 'full' );
       echo '</li>';
      }
    }
endwhile;

endif;
wp_reset_query();

最佳解決方案

使用 get_children

我使用這個代碼從選擇的順序從頁面庫中提取所有的圖像。您可以將此代碼包含在循環中或將其獨立使用。只需選擇適當的 post_parent 代碼 (見代碼示例) 。

此示例顯示與頁面 ID 1 相關聯的所有圖像,請查看:

        $images = get_children( array( 'post_parent' => 1, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => 999 ) );
/* $images is now a object that contains all images (related to post id 1) and their information ordered like the gallery interface. */
        if ( $images ) {

                //looping through the images
                foreach ( $images as $attachment_id => $attachment ) {
                ?>

                            <?php /* Outputs the image like this: <img src="" alt="" title="" width="" height="" /> */  ?>
                            <?php echo wp_get_attachment_image( $attachment_id, 'full' ); ?>

                            This is the Caption:<br/>
                            <?php echo $attachment->post_excerpt; ?>

                            This is the Description:<br/>
                            <?php echo $attachment->post_content; ?>

                <?php
                }
        }

找到你要從中提取圖像並將其插入到此參數中的帖子 ID:'post_parent' => 1(將 1 替換為您的頁面 ID)

你也可以使用:

'post_parent' => $post->ID

如果要在循環中使用 get_children,並從返回的帖子標識中獲取帖子 ID 。

如果要排除選定為特色圖像的圖像,我將使用 if 語句來檢查圖像 URL 是否等於特徵圖像 URL 。

希望這可以幫助! 🙂

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。