php - 将缩略图后设置为背景图像

标签 php jquery html css wordpress

我的 WordPress 网站显示所有帖子,这些帖子使用行(Bootstrap 3)堆叠在跨越整个索引宽度的文章中。

index.php - HTML

<div>
<?php if ( have_posts() ) : ?>

        <?php /* Start the Loop */ ?>
        <?php while ( have_posts() ) : the_post(); ?>

            <?php
                get_template_part( 'content' );
            ?>

        <?php endwhile; ?>
        <div class="clearfix"></div>
        <div class="col-md-12">
        </div>
    <?php else : ?>

        <?php get_template_part( 'no-results', 'index' ); ?>

    <?php endif; ?>
</div> 

content.php 显示每篇文章中的帖子(相互堆叠,全宽,位于页面下方)

<article id="post-<?php the_ID(); ?>" <?php post_class('container-fluid'); ?>>
<div class="row">
  <div class="col-md-12 horiz-cell">
    <h2><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
    <?php the_category(', '); ?>
  </div>    
</div>
</article><!-- /#post -->

我的标题和类别在每一行中都正确显示。我希望每个帖子的后缩略图(我在functions.php 中添加了它的使用)作为每行的背景图像。填充整个空间(背景大小:覆盖)

基本上很大,“100% 宽度”和“300px(大约)高度”行,每行都有相应的标题、类别及其后缩略图作为背景图像。

最佳答案

如果尚未完成,请启用缩略图并 define custom image sizes :

// Enable thumbnails
add_theme_support( 'post-thumbnails' );
add_image_size('my-fun-size',580, 480, true);

显示缩略图: 首先,获取帖子的特色图片 URL:

参数'my-fun-size'应该是您在functions.php文件中定义的图像大小的名称 - 它也可以是'full'或'缩略图'

<?php
if (has_post_thumbnail()) {
    $thumbnail_data = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'my-fun-size' );
    $thumbnail_url = $thumbnail_data[0];
}
?>

然后添加图像作为背景:

<article id="post-<?php the_ID(); ?>" style="background-image:url('<?php echo $thumbnail_url ?>')" <?php post_class('container-fluid'); ?> >
<div class="row">
  <div class="col-md-12 horiz-cell">
    <h2><a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
    <?php the_category(', '); ?>
  </div>    
</div>
</article><!-- /#post -->

最后,应用一些 CSS 来实现您想要的背景大小:

article {
  background-size: cover;
}

关于php - 将缩略图后设置为背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30056734/

相关文章:

html - Img 设置为最大宽度 : 100% is publishing larger than the actual image size?

php - 编码 php 和 python?

php - 调试 cron PHP 脚本

javascript - 在 PHP 中获取多个选择框的值并将它们添加到数组中

php - 服务器进程采用PHP+MySQL

javascript - 如何使用javascript将文本输入的值存储为字符串

jquery - 使用 jQuery 调整 Div 大小

javascript - 使用 highchart 设置符号标记

html - 具有图像背景的 Div 与 img 标签

html - bootstrap 3 没有用于 prismjs 代码突出显示的水平滚动条