Custom title background in WordPress using custom fields

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

[code=’css’]
#main-content h1 { background:url(g/htxt.jpg) no-repeat; }

[/code]

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

<

pre>

[/code]

after the line, I added this

<

pre>

ID, 'fondo', true); ?>

[/code]

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:

<

pre>

<

h1 style="background:url() no-repeat;">

Title Text

[/code]

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.

11 thoughts on “Custom title background in WordPress using custom fields”

  1. Muchas gracias Matt, y mil gracias por el link en Twitter!
    Estuve husmeando en tu sitio y encontré las functions.php que ofreces. La shorten_text me va a servir muchísimo en mi proyecto actual.
    Gracias, saludos!

  2. Хорошо пишете. Я бы конечно некоторые моменты оспорила, ну да ладно.

    Translated by Google T: Good writing. I would certainly challenged some points, well yes OK.

  3. I am definitely impressed along with your writing skills as well as with the page layout on your blog post. Is it a paid design or do you customize it yourself? In any case continue fantastic superior writing, it is unusual to discover a good web site just like this today..

Leave a Reply to Zoe Murphy Cancel reply