Quick custom text ad placement in WordPress blog categories

69

Author: Tina Gasperson

WordPress plugins abound for Google AdSense and other third-party text ad brokers, but what happens when someone wants to buy ad space directly from you, on a specific category page in your blog? You can easily add static HTML text ads to your category search result pages by creating category-specific page templates.

Because most WordPress themes have a single template for archives, aptly named archive.php, it’s not immediately apparent how to place a text ad on a specific category results page. But never fear: by default, WordPress searches using what it calls a “template hierarchy.” By taking advantage of the template hierarchy, it’s easy to make a special page that keeps your text ad where it belongs.

The template hierarchy works like this: if your visitor clicks on category #3, WordPress first looks for the most specific template: category-3.php. If it doesn’t find that, then it goes after the more generic category.php, and then archive.php, and if it doesn’t find that, it finally drops back to index.php. Armed with this knowledge, you can create a category-specific template using archive.php as a base. (Note: your categories probably have actual names, not numbers, but WordPress assigns ID numbers to categories, just as it does with pages and posts. If you don’t know the ID numbers off the top of your head, look in the administration panel under Manage -> Categories; the numbers are in that first column.)

To create your custom category page, open a copy of the archive.php file in a text editor and save it with a name that matches whatever category number you want to display the ad in — category-#.php. Place the static text ad into your new category-specific PHP file by surrounding the HTML code with <div id="sticky-snip"></div>. Then paste that snippet, including the div tags, into the file, directly under this line of code: <?php get_header(); ?> , as in this example. Save the file, upload it to wp-content/themes/your_theme, and you’re done.

Granted, this is static code in a dynamic page and therefore not the most elegant solution, but it works. You PHP wizards out there might have a better way to write this, especially for situations where you need to publish several different ads in different categories. In that case, we welcome your suggestions — or a new plugin.

Category:

  • PHP