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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度