I am working on a php/wordpress website in which I want to hide the background-color when there is no content.
The php code which I am using is:
<div class="featured-block__content">
<h1 class="featured-block__tag"><?php echo esc_html( explode('|',get_the_title())[1]); ?></h1>
</div>
The css code for the above html/php code is:
.featured-block__content {
display: flex;
justify-content: center;
align-items: center;
height: 85px;
background-color: rgb(255, 255, 255);
opacity: 0.831;
z-index: 3;
position: relative;
bottom: 85px;
}
Problem Statement:
I am wondering what changes I need to make in the php code above so that where there is no content inside h1 tag, the background-color should be background-color: rgba(0, 0, 0, 0);
At this moment where there is content inside h1 tag, the background-color is background-color: rgb(255, 255, 255);
You can use the following:
<?php
$h1_content = esc_html(explode('|', get_the_title())[1]);
?>
<div class="featured-block__content <?= trim($h1_content) === '' ? 'no-h1' : ''; ?>">
<h1 class="featured-block__tag"><?= $h1_content; ?></h1>
</div>
With the following additional CSS:
.featured-block__content.no-h1 {
background-color: rgba(0, 0, 0, 0);
}
In order to have PHP control the CSS, you'll need to output a new rule to DOM that the CSS can target.
In this case, you can add a class to the <h1>
, by simply echo
ing out the desired class name when there's no content. esc_html()
returns an empty string, so you can do a check against ""
.
The following adds a class black
when this content is absent:
<h1 class="featured-block__tag" <?php if (esc_html(explode('|',get_the_title())[1]) === "") { echo "black"; } ?>>
<?php echo esc_html(explode('|',get_the_title())[1]); ?>
</h1>
From here you can craft CSS that applies the desired rule to the new selector:
.black {
background-color: rgb(0, 0, 0);
}
You can try
<h1 class="<?php esc_html( explode('|',get_the_title())[1]) === '' ? 'featured-block__tag bg-class1' : 'featured-block__tag'?>"><?php echo esc_html( explode('|',get_the_title())[1]); ?></h1>
and css
.bg-class1{
background-color: #yourcolor
}