Displaying a random blogroll link

We are going to make a simple function in WordPress to fetch a random blogroll from the WP database and display it as a link.

Place the following lines of code in your theme’s function.php file.

1
2
3
4
5
6
7
8
9
10
11
12
function random_blogroll($number=1) {
        global $wpdb;
        $query = "SELECT link_url, link_name, link_description FROM $wpdb->links WHERE link_visible = 'Y' ORDER BY rand() LIMIT ".$number;
        $results = $wpdb->get_results($query);
        foreach ($results as $result) {
            $link_url = $result->link_url;
            $link_name = $result->link_name;
            $link_description = $result->link_description;
                $retsrting .= '<a href="'.$link_url.'" rel="external" title="'.$link_name.'">'.$link_name.'</a> ';
            }
            return $retsrting;
    }

To display the random link in your blog, place the following code where you want the link(s) to appear:

1
if(function_exists('random_blogroll')) echo random_blogroll();

To display ‘x’ number of links, pass the number as a parameter to the function

1
2
/* Example - To display 4 Blogroll links */
if(function_exists('random_blogroll')) echo random_blogroll(4);

Posted by

Deepak Thomas is a guy who hearts wordpress. If you're having trouble with wordpress, tweet it with @thinkdj and he'll try to solve your queries for a box of chocolates.

Leave a Reply

Required fields are marked *.


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>