简体   繁体   English

在我自己的 wordpress 主题中添加 the_post_thumbnail 作为 CSS 背景

[英]adding the_post_thumbnail as CSS Background, in my own wordpress theme

I am trying to setup my blog homepage to show the featured image and the title, so far everything is coming out fine except for some reason my code to add in the image is having issues even trying to follow what many other posts here have seemed to answer.我正在尝试设置我的博客主页以显示特色图片和标题,到目前为止,一切都很好,除非出于某种原因,我添加到图片中的代码出现问题,甚至试图遵循这里的许多其他帖子似乎也有问题回答。 Here is my code:这是我的代码:

<div class="blogContainer">
<?php
  while(have_posts()) {
    the_post();?>
    <?php $thumb = get_the_post_thumbnail_url(); ?>
    <div class="blogItems" style="background-image: url('<?php echo $thumb;?>')">
      <a href="<?php the_permalink(); ?>"><h4><?php the_title();?></h4></a>
    </div>
<?php } ?>

I've tried a couple small variations such as this:我尝试了几个小的变化,例如:

    <?php
  while(have_posts()) {
    the_post();?>
    <?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>
    <div class="blogItems" style="background-image: url('<?php echo $url; ?>')">
      <a href="<?php the_permalink(); ?>"><h4><?php the_title();?></h4></a>
    </div>
<?php } ?>

And this和这个

    <?php
  while(have_posts()) {
    the_post();?>
    <?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); ?>
    <div class="blogItems" style="background-image: url('<?php echo $backgroundImg[0]; ?>');">
      <a href="<?php the_permalink(); ?>"><h4><?php the_title();?></h4></a>
    </div>
<?php } ?>

And all come out with the same issue of having the url just come up empty in the inspect tab.并且所有都出现了相同的问题,即在检查选项卡中将 url 显示为空。 If someone has an answer it'd be much appreciated!如果有人有答案,将不胜感激!

Please try below code:请尝试以下代码:

<?php
$args = array(
    'post_type' => 'post', //change with your post type
    'posts_per_page' => -1
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
    $thumb = get_the_post_thumbnail_url(); ?>
        <div class="blogItems" style="background-image: url('<?php echo $thumb;?>');">
            <a href="<?php the_permalink(); ?>"><h4><?php the_title();?></h4></a>
        </div>
<?php endwhile; endif; ?>

Try adding get_the_ID() to get_the_post_thumbnail_url() in the first example:尝试在第一个示例中将 get_the_ID() 添加到 get_the_post_thumbnail_url() :

<div class="blogContainer">
<?php
  while(have_posts()) {
    the_post();?>
    <?php $thumb = get_the_post_thumbnail_url(get_the_ID()); ?>
    <div class="blogItems" style="background-image: url('<?php echo $thumb;?>')">
      <a href="<?php the_permalink(); ?>"><h4><?php the_title();?></h4></a>
    </div>
<?php } ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM