In my last WordPress implementation I had to show different backgrounds for the page title. One title said “Who we are” with a background of several people. Another page title said “Our services” and the background image was only one man and one girl engaging in a conversation. To achieve this I used the custom fields.
Basic styling
#main-content h1 { background:url(g/htxt.jpg) no-repeat; }
This would be the common background if we don’t apply the custom fields technique.
In the Write Page area
The job in Write Page is simple, I uploaded an image using “add and image” and copied the link. I added a custom field with key “fondo” and the link as the value.
Adding code to page.php
I found this line in page.php, the template file that WordPress uses to define the layout for pages
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
after the line, I added this
<?php $estilo = get_post_meta($post->ID, 'fondo', true); ?>
There’s one variable $estilo, that is assigned the value of the custom field “fondo”, according to the post ID. Now, I could’ve go and style everything using the variable, but what happens if someone creates a new page and forgets to add a custom background? in that case we would see the image broken. We need to check whether the variable has the value we need in order to proceed. If it doesn’t, the regular background from our stylesheet will show. If it does, we will style the <h1> tag. Let’s find the title tag and wrap it with the necessary code:
<?php if ($estilo != '') { ?>
<h1 style="background:url(<?php echo $estilo; ?>) no-repeat;">
<?php }else{ ?>
<h1>
<?php } ?>
<?php the_title(); ?>
Title Text
</h1>
Since $estilo has the full path that we copied from the media manager all we have to do is a simple echo. That’s it, of course, you should set up all the background relative options since the style applied will overwrite everything leaving in a blank state before applying the background style. If you had defined a color, define it again, if the background repeats or not, position, etc.
Tags: resources