• Resolved kitykitykity

    (@kitykitykity)


    Hello all,

    I have written some code that shows 12 random images that are post attachments. It shows them as thumbnails (with br’s between them, so I can use it in my sidebar).

    I realized there were some images I wanted to exclude from showing in the sidebar (icons, emojis I have uploaded, etc). So I created an array with the media IDs that I don’t want to show.

    I don’t have something quite right. Those images are still showing up in the random results that are used in my sidebar. Could you take a look and let me know what I’m missing? I’m wondering if something should be in quotes that isn’t, etc. (You’ll see I went ahead and enclosed all the IDs in single quotes, but that didn’t fix it)…

    Unfortunately the page itself is private, so I can’t show you; but hopefully someone can look at the code and see what I’m doing wrong.

    Thanks a whole bunch in advance!

    <?php
      $bads = array ('9611', '10031', '10446', '10450', '10577', '10723', '10724', '10725', '10726', '10727', '10728', '10730', '10731', '10732', '10733', '10734', '10735', '10736', '10737', '10738', '10739', '10740', '10741', '10742', '10743', '10744', '10745', '10746', '10747', '10748', '10749', '10750', '10751', '10752', '10753', '10754', '10755', '10756', '10757', '10758', '10759', '10764', '11511', '12597', '12637', '13449', '15171', '16156', '16306', '16320', '16359', '16403');
      if ( have_posts() ) : while ( have_posts() ) : the_post();    
        $args = array(
        'post_type' => 'attachment',
        'numberposts' => -1,
        'post_status' => null,
        'post_parent' => $post->ID
         );
    
        $attachments = get_posts( $args );
        if ( $attachments ) {
          foreach ( $attachments as $attachment ) {
    
    if (!in_array($attachment, $bads)) {
          $arr[] = wp_get_attachment_link( $attachment->ID, 'thumbnail', true );
    }
    
          }
        }
      endwhile;
    endif; 
    
    for ($i = 1; $i <= 12; $i++) {
      $rnd = array_rand($arr, 1);
      echo $arr[$rnd];
      echo '<br /> <br />';
    }
    ?>
    
Viewing 2 replies - 1 through 2 (of 2 total)
  • You’re checking the whole attachment post object rather than the attachment ID.

    Change the line to if (!in_array($attachment->ID, $bads)) {

    Thread Starter kitykitykity

    (@kitykitykity)

    That appears to have worked perfectly. Thank you for your prompt response! I was staring at it too long… ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Exclude images from displaying’ is closed to new replies.