Custom Fields are a nice feature in WordPress that allow you to include content that is separate from your main post or page. This is useful if you want to include a different image in your header depending on the post or page ID or if you want to show differant banner ads for individual posts. For this example I’m going to include a custom banner ad above the main content of the post.
Part 1: Adding the Custom Field to the post
The first stage is adding the custom field name and value to the post in question. Later you will display that value in the template file using PHP.
- Start by opening the post where you wish to include the banner
- Scroll down to the Custom Fields area below the main editor
- Enter a custom field name in the name section
- Click ‘Update’ to save changes
<a href=”http://yourdomain.com”><img title=”banner” src=”http://domain.com/images/banner.png” alt=”Spartix” width=”468″ height=”60″ /></a>
Remember to replace ‘yourdomain.com’ with the URL you want to link to and the image src with the actual image source!
Part 2: Adding the code to your template
To display the Custom Field value you mush add some code to the Single Post template.
- Go to Appearance > Editor
- On the right hand side of the page open the Single Post template
- Scroll down and position your cursor immediately before where it says <?php the_content(
- Include the following code:
- Click ‘Update File’
<?php $ad = get_post_meta($post->ID, ‘ad_banner’, $single=true); echo $ad;?>
Navigate to the post where you added the custom field. You be able should see your banner ad directly above your main content.