PHP Simple Link Rotator Script

Here is a tutorial on creating a simple link rotator using rand() function and array on PHP. This tutorial is meant to be simple so you can modify the script to meet your requirements before use it into your website. Basically, the technique can be applied on creating images or banner rotator. By doing that, you got yourself a banner rotator you can use to display random advertisement.

Step by step

To do this, we need to create an array to put our links. Here’s how

<?php $links = array('link 1','link 2','link 3'); ?>

Replace link 1, link 2 and link 3 to the HTML code of your link. We can easily add more data in the array.

Here’s an example of HTML code for a link

<a href="http://linkurl.com" />text to display</a>

We can replace the text to display with an image. Here’s the exapmle of HTML code to show an image

<img src="http://image_url.com" alt="alternate text" />

Then we need to generate random number before we display the link.

<?php
$max = count($links)-1;
$rand = rand(0, $max);
?>

Now that we already got the random number, you ready to display the link using this code

<?php print $links[$rand]; ?>

Using this script on more than a page

In order to use this link on more than a page on our website, we need to write the script on a separate page and include the page in the other page. This is saving our times more then writing the code in every other page. For more information on how to include pages on PHP, refer to this article.

Applying this script on WordPress blog

To easily use this script on WordPress blog, first we need to write the script into a PHP function and add the function into our header.php template.

Open your header.php. Find the <body> tag and add this script before the tag.

<?php
// Function to generate a random link
function link_rotator() {
	$links = array('link 1','link 2','link 3');
	$max = count($links)-1;
	$rand = rand(0, $max);
	print $links[$rand]; //
}
?>

Open a template file and add this code below somewhere on the template to display the link on other template.

<?php link_rotator(); ?>
11 comments on "PHP Simple Link Rotator Script"
Leave a Response