0

i'm trying to get post's first image(LINK) , Currently i'm using Shorcodes Ultimade plugin for it so far i'm able to get post's content using the following shortcode on my static homepage page

[su_post field="post_content" default="" before="" after="" post_id="68" filter=""]

but the above shortcode is returning the whole content (Images + Post's text)

i checked the documentation and they don't seem to have any built in solution for getting only image from a post, Any one know how can i get only the image or can i filter out only image from returned data?

1
  • 1
    You could theoretically run a preg_match on the post content and search for the image-tag but that is no good idea. Why not use the featured image function of WordPress?
    – flomei
    Commented Jul 22, 2018 at 22:36

1 Answer 1

2

I would rewrite a simple shortcode to retrieve only post images:

add_shortcode( "postImages", "stack_309224_attachhment" );

function stack_309224_attachhment($atts){
extract(shortcode_atts( array(
  'id'      => 1, // default id of the post
  "max"   =>4 ,// default max number of images to display
  "featured"=>"false" // if to retrieve the post featured image or not, default false
),  $atts ));

ob_start();
if($atts['featured']=="true"){ // display only the featured image
  ?>
  <figure><img src="<?php echo wp_get_attachment_image_src(get_post_thumbnail_id( (int)$atts['id']) )[0]?>" /></figure>
  <?php
}
else{ // display a gallery of attached images within  "max" attr.
  $images=get_attached_media( 'image', (int)$atts['id'] );
  if(count($images) > 0 ){
   ?>
   <div class="gallery">
   <?php
   $index=0;
   foreach($images as $image){
     if($index < (int)$atts['max']){ //display image only if within max 
    ?>
    <figure><img src="<?php echo wp_get_attachment_url($image->ID)?>" /></figure>
    <?php
      $index ++;
     }
   }
 ?></div><?php
 }     
}
return ob_get_clean();
}

Then in the wp editor you can use:

  • [postImages id=2387 featured="true"] -> displays only featured image for post #2387

  • [postImages id=2387 max = 4] -> displays a gallery of 4 images attached to post #2387

2
  • Firstly thank you for helping me out, i was struggling with this from a long time now. this is exactly what i need. one question how can i query for the image on it's full size? currently them image that i'm receiving is 150*150
    – remy boys
    Commented Jul 23, 2018 at 0:26
  • 1
    try wp_get_attachment_image_src(get_post_thumbnail_id( (int)$atts['id']),'medium' )[0]; OR wp_get_attachment_image_src(get_post_thumbnail_id( (int)$atts['id']),'full' )[0]; Commented Jul 23, 2018 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.