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

报告相同问题?