如何在WordPress中检查缩略图?

jor*_*ame 5 php wordpress wordpress-theming

我怎样才能检查帖子是否有缩略图以及是否有效?如果不做其他事情.这就是我所拥有的:

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

                <?php if ( has_post_thumbnail() ) { ?>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                <?php 
                }else{ 
                ?>
                    <?php the_post_thumbnail(); ?> 
                <?php
                } 
                ?>  

            <?php endwhile; ?>

        <?php endif; ?>
Run Code Online (Sandbox Code Playgroud)

任何帮助将是欣赏它.

eve*_*ans 6

你已经有了这个,在行

if ( has_post_thumbnail() )
Run Code Online (Sandbox Code Playgroud)

你正在检查帖子是否有缩略图,问题是你在else语句中输错了代码,你必须输入如下内容:

  <?php if ( has_post_thumbnail() ) { ?>
      <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
      <?php the_post_thumbnail(); ?> 
      HAVE THUMBNAIL DO SOMETHING
  <?php 
      }else{ 
  ?>
      DOESN'T HAVE THUMBNAIL : DO SOMETHING ELSE
      <?php
  } 
  ?>  
Run Code Online (Sandbox Code Playgroud)


Mar*_*rty 0

首先检查你的functions.php文件

if (function_exists('add_theme_support')) {
  add_theme_support('post-thumbnails');
}
Run Code Online (Sandbox Code Playgroud)

如果它不在那里,请将其复制并粘贴到您的文件中。

其次,将其添加到您的functions.php中,这可以让您返回图像src,而不仅仅是打印整个img标签

function get_the_post_thumbnail_url( $post_id = NULL ) {
    global $id;
    $post_id = ( NULL === $post_id ) ? $id : $post_id;
    $src = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'full');
    $src = $src[0];
    return $src;
}
Run Code Online (Sandbox Code Playgroud)

然后在模板页面上将代码更改为以下内容: 这被用作背景图像

<?php if ( has_post_thumbnail() ) { ?>
    <div id="slider" style="background-image:url(<?php echo get_the_post_thumbnail_url($post->ID, 'large'); ?>); background-position: center center;">  
    </div>                
<?php 
}else{ 
?>
    <img src="<?php bloginfo('template_directory');?>/images/blank.jpg" alt="" /> 
<?php
} 
?> 
Run Code Online (Sandbox Code Playgroud)

这应该会生成一个带有背景图像的 div,

如果您想打印完整的 img 标签代码,只需使用以下方法之一。

if (has_post_thumbnail()) { 
?>
    <?php the_post_thumbnail();            // just the image        ?>
    <?php the_post_thumbnail('thumbnail'); // just the thumbnail    ?>
    <?php the_post_thumbnail('medium');    // just the Medium Image ?>
    <?php the_post_thumbnail('large');     // just the Medium Image ?>
    <?php 
    // adding a 200x200 height and width along with a class to it.
        the_post_thumbnail(array( 200,200 ), array( 'class' => 'alignleft' )); 
    ?>
    <?php 
    // Adding a few classes to the medium image
        the_post_thumbnail('medium', array('class' => 'alignleft another_class')); 
    ?>

<?php
}
Run Code Online (Sandbox Code Playgroud)

马蒂..