1

I want to show both posts and attachments in the search results. Basically, I need something that says if the post has a thumbnail, show it. else show the attachment image (since they don't have thumbnails and are being pulled directly from the media library).

This is what I've tried onsearch.php, but it didn't work:

<?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>

        <?php
            echo '<a class="search-item">';
            if( has_post_thumbnail() ) { 
                $image_src = the_post_thumbnail( 'custom-size', array( 'class' => "img-style" ) );
            }
            else {
                $image_src = wp_get_attachment_image_src( 'custom-size', array( 'class' => "img-style" ) );
                echo '</a>';
            }
        ?>

    <?php endwhile; ?>
<?php endif; ?>
1

The wp_get_attachment_image_src() function expects you to also pass some kind of attachment ID plus it doesn't grab the image HTML that we need so instead we should use wp_get_attachment_image().

IF a post has a post thumbnail, grab it.
ELSE IF the post has any attached images, grab the first one.
ELSE maybe show a placeholder? I've defined the else case at the top of the loop as a default.

if( have_posts() ) {
    while( have_posts() ) {
        the_post();
        $image_html = ''; // assign placeholder url here?

        if( has_post_thumbnail() ) {
            $image_html = get_the_post_thumbnail( $post->ID, 'custom-size', array( 'class' => 'img-style' ) );
        } else { // We don't have a thumbnail - grab attachments
            $media = get_posts( array(
                'post_type'         => 'attachment',
                'posts_per_page'    => 1,
                'post_status'       => 'any',
                'post_parent'       => $post->ID
                'post_mime_type'    => array( 'image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'image/x-icon' );
            ) );

            if( ! empty( $media ) ) {
                $image_html = wp_get_attachment_image( $media[0]->ID, 'cusotm-size', false, array( 'class' => 'img-style' ) );
            }
        }

        if( ! empty( $image_html ) ) {
            echo '<a href="'. get_permalink() . '">' . $image_html . '</a>';
        }
    }
}

Note, I haven't tested the above so feel free to refine it.

  • 1
    Thank you! That was exactly the right direction I needed to go. My final code looks lie this: if(has_post_thumbnail()) { the_post_thumbnail( 'custom-size', array( 'class' => "img-style" ) ); echo '</a>';} else { echo '<img class="img-style" src="'.wp_get_attachment_url ().'"/>'; }?> <?php //End the post loop endwhile; else: ?> – BlueHelmet May 18 '16 at 3:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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