Forums

[resolved] Output attachments not attached to post that match a custom field (4 posts)

  1. erichmond
    Member
    Posted 1 year ago #

    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 } ?>
  2. vtxyzzy
    Member
    Posted 1 year ago #

    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';
    }
  3. erichmond
    Member
    Posted 1 year ago #

    Awesome! Worked a treat thanks very much!

  4. zoonini
    help me help you
    Posted 1 year ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic