1

I currently have the <?php the_post_thumbnail('post-thumbnail', array( 'class' => "search-thumb attachment-post-thumbnail")); ?> inside of a div that holds the Search Result Title, and Excerpt. What I'm trying to achieve is ONLY adding the thumbnail if the post has it available.

My reason for this is because adding a thumbnail will make the div's height larger. Let's say the div with the thumbnail is 150px in height. I'd like to eliminate the height and have the div fit ONLY the text if the search result has no thumbnail.

HTML within search.php//

<?php get_header(); ?>

<div id="container" class="clearfix">
<div id="content-wrap">

<h1 class="heading1">Search Results</h1>
<div class="br"></div>

<div class="clear"></div>
<h2><?php echo 'Items Found ' . $wp_query->found_posts; ?></h2>
<div class="clear"></div>

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


    <div class="s-res">
    <h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>
    <div class="search-thumb">
            <?php the_post_thumbnail('post-thumbnail', array( 'class'   => "search-thumb attachment-post-thumbnail")); ?>
        </div>
    <?php echo str_replace('[...]', '', get_the_excerpt()); ?>
    </div>

    <?php endwhile; ?>
    <?php else : ?>
    <i><?php _e('Sorry, but nothing matched your search criteria.<br> Please try again with different keywords.'); ?></i>
    <?php endif; ?>

</div>
</div>





<?php get_footer(); ?>

CSS to show height ect//

.s-res {
    height: 150px;
    margin-bottom: 10px;
}

img.search-thumb {
    float: left;
    background: url(images/diag_lines.png) repeat;
    height: 100px;
    padding: 10px;
}

SCREENSHOT//

screenshot

4

1 回答 1

3

只需将缩略图 div 包装在if ( has_post_thumbnail() ) {...条件块中即可。当您使用该函数时,您的代码应如下所示:

<?php get_header(); ?>

<div id="container" class="clearfix">
<div id="content-wrap">

<h1 class="heading1">Search Results</h1>
<div class="br"></div>

<div class="clear"></div>
<h2><?php echo 'Items Found ' . $wp_query->found_posts; ?></h2>
<div class="clear"></div>

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

    <div class="s-res">
    <h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>
    <?php if ( has_post_thumbnail() ): ?>
        <div class="search-thumb">
            <?php the_post_thumbnail('post-thumbnail', array( 'class'   => "search-thumb attachment-post-thumbnail")); ?>
        </div>
    <?php endif ?>
    <?php echo str_replace('[...]', '', get_the_excerpt()); ?>
    </div>

    <?php endwhile; ?>
    <?php else : ?>
    <i><?php _e('Sorry, but nothing matched your search criteria.<br> Please try again with different keywords.'); ?></i>
    <?php endif; ?>

</div>
</div>

<?php get_footer(); ?>

我建议您在提出问题之前先进行快速的Google搜索;)这个功能很容易找到,此外 WordPress 有一个很好的代码文档,所以您很有可能找到答案你的大部分问题都在那里。

于 2012-11-15T12:48:27.160 回答