使用img src属性中的if语句的WordPress特征图像

时间:2017-04-11 08:17:19

标签: php html wordpress twitter-bootstrap

我使用if has_post_thumb函数访问WordPress中自定义帖子类型的要素图像。一切都很好,除了在img标签中的尾随>“实际上是在页面上显示。我只是写错了吗?我必须将php保留在src属性中,因为img标签中有一些重要的Bootstrap类。请见下面的代码:

                    <!-- create new loop and access custom post type for services using wordpress fxn -->
                    <!-- create var called loop and store a WP array for custom post type (CPT) services offered, ordered by id and ascending -->
                    <?php $loop = new WP_Query( array( 'post_type' => 'accolades', 'orderby' => 'post_id', 'order' => 'ASC') ); ?>

                    <!-- check to see if loop has posts and access posts from CPT. Same for all CPT -->
                    <?php while( $loop->have_posts() ) : $loop->the_post(); ?>

                        <!-- no acf used below it is all native WP using CPT -->
                        <div class="col-sm-4">
                            <div class="row">
                                <div class="col-sm-3">
                                    <!-- check if there is a post thumbnail img or feature image. this grabs the feature img if there is one below. add an else statement to the if to display image if none uploaded -->
                                    <img class="img-responsive img-circle" src="<?php if( has_post_thumbnail() ){ the_post_thumbnail(); } ?>">
                                </div><!-- /.col-sm-3 -->
                                <div class="col-sm-9">
                                    <blockquote>
                                    <!-- CPT content in content editor -->
                                        <p><?php the_content(); ?></p>
                                        <!-- CPT title -->
                                        <small><?php the_title(); ?></small>
                                    </blockquote>
                                </div><!-- /.col-sm-9 -->
                            </div><!-- /.row -->
                        </div><!-- /.col-sm-4 -->

                    <!-- close the while loop -->
                    <?php endwhile; ?>

3 个答案:

答案 0 :(得分:1)

the_post_thumbnail()函数已经返回图像而不是url。请改用_post_thumbnail_url()。

请参阅https://developer.wordpress.org/reference/functions/the_post_thumbnail/ https://codex.wordpress.org/Function_Reference/the_post_thumbnail_url

答案 1 :(得分:0)

尝试这样:

if(has_post_thumbnail()){
  echo "<img class='img-responsive img-circle' src='your image'>"
}
else{
   echo "<img class='img-responsive img-circle' src='your image'>"
}

OR

<?php echo ((has_post_thumbnalil()) ? the_post_thumbnail() : '' )?> 

答案 2 :(得分:0)

你可以这样:

 <?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 
 'thumbnail' ); ?>
  <img src="<?php echo $url ?>" />