Fetch images only from wordpress posts

In wordpress, when a post category (or tag) is clicked, all posts that match the clicked category (or tag) is returned, because of <?php the_content(); ?>

In my case, every post has an image in it, so how can I only fetch the images when a category (or tag) is clicked? I’m not familiar what code I need to use.

Read More

Update: I’m trying not to use plugins. My apologies for not mentioning that earlier. What I’m trying to achieve is something like The Sartorialist – All posts have images, click on any category (or tag) associated with any post and only images are fetched.

Update 2: I tried this:

 <?php   

 $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>';
           echo wp_get_attachment_image( $attachment->ID, 'full' );
           echo '</li>';
          }
     }

 ?>

The only weird thing is, and I’m trying to figure out, another image from the media library also shows up, without it being in any of my posts.

I also found this plugin which is very close to what I want, but unfortunately it has to be in a separate page, not the in category page.

Related posts

Leave a Reply

1 comment

  1. You can achieve this with something like this:

    <?php
    
    function getImage($num) {
    global $more;
    $more = 1;
    $link = get_permalink();
    $content = get_the_content();
    $count = substr_count($content, '<img');
    $start = 0;
    for($i=1;$i<=$count;$i++) {
    $imgBeg = strpos($content, '<img', $start);
    $post = substr($content, $imgBeg);
    $imgEnd = strpos($post, '>');
    $postOutput = substr($post, 0, $imgEnd+1);
    $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
    $image[$i] = $postOutput;
    $start=$imgEnd+1;
    }
    if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; }
    $more = 0;
    }
    
    ?>
    

    source