Easy Way For Advertisement In WordPress

Since version 2.5 WordPress introduced the shortcode API, more detail about it in our article „WordPress Shortcode API“. Recently I had a task which is surely common, but with the help of shortcode API and custom fields very easy to solve. I had to include some advertisements (in german: Werbung) into some articles.

In each article the editor puts 3 custom fields: bild (image), link, linktext. In the text he can set the shortcode [ad]. This shortcode will be recognized by WordPress with the help of the following function. It will also load specific data to display the ads here.

Easy advertisement with shortcode-API in WordPress

Easy advertisement with shortcode-API in WordPress

The following function can be used as Plugin or put in functions.php of your theme.

function example_link() {
	global $wp_query;

	$postID     = $wp_query->post->ID;
	$mylink     = get_post_custom_values('link', $postID);
	$mypic      = get_post_custom_values('bild', $postID);
	$mylinktext = get_post_custom_values('linktext', $postID);

	return '<a href="' . $mylink[0] . '"><img title="' . $mylinktext[0] . '" src="' . $mypic[0] . '" alt="" /></a>';
}

add_shortcode('werbung', 'example_link');

In your content it will display the image with the link and link text. This is just an example and there are many other possibilities to use this. Of course you could get the data for link, image and link text from the other data fields, but a shortcode API makes it easier to include something like this in their post.

Comments are closed.

7 comments

  1. Mehdi

    Great and easy!!!

  2. Daichi

    Thank you very much. Nice n easy

  3. Tom Coady

    When you say "The following function can be used as Plugin or put in functions.php of your theme." is this an optional step? I got as far as adding the custom field but it renders in preview as [customid] so I'm not sure if I also need to add code to functions.php

    Also there's a plugin that enables this where you define any text with a code like :this: and it will automatically display whatever that's defined to, which for me is a bit simpler than editing the php, assuming this is necessary.

4 pingbacks

  1. Mastering WordPress Shortcodes | Developer's Toolbox | Smashing Magazine
  2. Mess like the Best: Wordpress Shortcodes: | Orange Market
  3. Mastering WordPress Shortcodes | Bookmarks
  4. Geek is a Lift-Style. » Blog Archive » Mastering WordPress Shortcodes