WordPress Hero Section

Chris Ashman
3 min readJun 20, 2021

Hello everyone, it has been two weeks since my last technical blog, but I am happy to share this PHP knowledge that I learned from my project at my internship. As I mentioned two weeks ago, I would like to go over the different sections of my project. This week I want to talk about the Hero Section. The hero section is the large banner that you see on most websites. It can contain a variety of designs such as a picture in the background with buttons in the foreground, a revolving carousel of images, or many different designs depending on the designer of the site.

Hero Banner

In the case of my project, I created a simple hero image in the background with the title of the image in the foreground. My mentor wanted me to use the advanced custom fields plugin so I can get more acquainted with it. Now, the creation of the hero banner is much easier in code than the actual creation. In ACF, we have fields that we can fill out to connect the plugin with our code. I need to create a field group called Hero that will contain our headline text and the image. I called the image, hero_image, and the text, hero_headline. The reason I did this is that I wanted to make it easier when translating the information to PHP. Next, I had to upload an image to the WordPress media gallery for when I select an image for the hero_image.

After I did those two things in the WordPress admin, it was time to put that into code form. This was more of an easier part of the creation since it was a couple of lines of code.

<div id="hero"><div class="hero-text"><h2><?php the_field('hero_headline'); ?></h2></div><?php$hero = get_field('hero_image');if ( $hero ): ?><style>#hero {background-image: url(<?php echo $hero; ?>);}</style><?php endif; ?></div></div>

In the code above, I created two divs that would contain the information that would go in the hero section. I made a PHP code that calls the hero_headline text from ACF and that text would get render out as Valstrax: The Star of Despair. The reason it gets render out like this is because of what I wrote in that section during the website creation.

I next made a variable called the hero and set its value to the get_field of hero_image. When hero_image gets rendered out, it will show whatever image I assigned to it during the website creation. I wrote out an if statement that checks if the $hero variable is true, if true it will echo or render the assigned image into the background. I closed the PHP section and closed the divs.

As you can see from the small code I wrote out that creating a hero section is not hard in code, it is more of the preparation stages in the WordPress admin that is a little bit time-consuming. Next time, I will talk about the creation of the Call to Action and what I did. See you next time!

--

--