• With my current code I can run a condition to check if a custom field is not empty then echo out an image.
    Otherwise check the media library and match another variable which is a custom field, if it matches use that image from the media library but if not I want to echo out a generic image.
    The problem with my code is if I have 10, 20, 30 images in my media library it will loop through with the foreach and output as many images even if there isn’t a match I get nontvimg.jpg as many times as there are images in the library, but I only want one. Is there a better way of doing this than my current code?

    <?php
                if ($imgurlbase != '' ) { ?>
    
                <img src="<?php bloginfo('template_url'); ?>/timthumb.php?src=<?php echo $imgurlbase . $imgfromtv; ?>&h=62&w=75" alt="<?php echo $programme; ?>">
    
    			<?php } elseif ($imgurlbase == '' ) { ?>
    
                    <img src="<?php bloginfo('template_url'); ?>/timthumb.php?src=<?php
                    $args = array(
                        'post_type' => 'attachment',
                        'numberposts' => -1,
                        'post_title' => $programme
                        );
                    $attachments = get_posts( $args );
    
                        foreach ( $attachments as $attachment ) {
    
                            if ($attachment->post_title == $programme) {
                                    echo wp_get_attachment_url($attachment->ID);
                                }
    						elseif ($attachment->post_title != $programme) {
    							echo '/images/nontvimg.jpg';
    						}	
    
                        }
                    ?>&h=62&w=75">
    
    			<?php } ?>
Viewing 3 replies - 1 through 3 (of 3 total)
  • Try coding it like this:

    $attachments = get_posts( $args );
    
    $found = 0;
    foreach ( $attachments as $attachment ) {
       if ($attachment->post_title == $programme) {
          echo wp_get_attachment_url($attachment->ID);
          ++$found;
       }
    }
    if (!$found) {
       echo '/images/nontvimg.jpg';
    }
    Thread Starter Elliott Richmond

    (@erichmond)

    Awesome! Worked a treat thanks very much!

    Glad you got this fixed. If you would please mark this thread as “resolved” it’ll help everyone keep better track of whose issues are still outstanding. Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Output attachments not attached to post that match a custom field’ is closed to new replies.