dongshen7561 2014-08-24 18:13
浏览 34
已采纳

在wordpress中从页面获取图像

I'm attempting to grab only the images from a page in Wordpress.

I read there was a function called get_post_gallery() but it doesn't seem to obtain my images. This is what I did:

if ( get_post_gallery() ) :
   $images = get_post_gallery(get_the_ID(), false);

   foreach($images as $image)
   {
      echo $image['src'];
   }
endif;

This line of code is put inside the loop from what I understand like so:

if ( have_posts() ) {
   \\Bit of code in here
}

However, the array that it returns appears to be empty (even though there are images in the post page editor). Do you guys suggest this way or another way to retrieve only images from a post/page?

  • 写回答

1条回答 默认 最新

  • douzhan3900 2014-08-24 18:21
    关注

    I've found your answer in another SO question.

    Here it is:

    function wpse_get_images() {
        global $post;
        $id = intval( $post->ID );
        $size = 'medium';
        $attachments = get_children( array(
                'post_parent' => $id,
                'post_status' => 'inherit',
                'post_type' => 'attachment',
                'post_mime_type' => 'image',
                'order' => 'ASC',
                'orderby' => 'menu_order'
            ) );
        if ( empty( $attachments ) )
                    return '';
    
        $output = "
    ";
    /**
     * Loop through each attachment
     */
    foreach ( $attachments as $id  => $attachment ) :
    
        $title = esc_html( $attachment->post_title, 1 );
        $img = wp_get_attachment_image_src( $id, $size );
    
        $output .= '<a class="selector thumb" href="' . esc_url( wp_get_attachment_url( $id ) ) . '" title="' . esc_attr( $title ) . '">';
        $output .= '<img class="aligncenter" src="' . esc_url( $img[0] ) . '" alt="' . esc_attr( $title ) . '" title="' . esc_attr( $title ) . '" />';
        $output .= '</a>';
    
    endforeach;
    
        return $output;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒