How to add a Link to a Random WordPress Post without using a plugin

Just add this WordPress Code Snippet below to the functions.php file in your current WordPress theme to allow you to add a link to a random WordPress post without using a plugin. This is the function I used to add the “Jump To A Random Snack” Button Link in the bottom of the right sidebar here at WPSnacks.

/**
 * Link to a Random WordPress Post
 *
 * @author WPSnacks.com
 * @link http://www.wpsnacks.com
 */
function addrandomlink() {
	$random_post = get_posts('posts_per_page=1&orderby=rand');
	$link = '<a href="'.get_permalink($random_post[0]->ID).'" title="Jump to Random Post: '.get_the_title($random_post[0]->ID).'">Jump To A Random Post</a>';
	echo '<div id="randomlink">';
	echo $link;
	echo '</div>';
}
add_action('enter_your_site_hook_here', 'addrandomlink');

As you can see, I wrapped the Random Post Link in a div named randomlink. This allows you to add style attributes for the random link through your CSS Stylesheet. You will need to replace enter_your_site_hook_here with whatever hook you want to use for the location you want your Random Post Link inserted. For example I used this line below in my function since WPSnacks is running on the Genesis Framework and I wanted the Random Post Link in the bottom of the sidebar:

add_action('genesis_after_sidebar_widget_area', 'addrandomlink');

Hope this helps. Enjoy.

   Related Sponsored Links

Disclaimer: The information contained in this website is for general information purposes only and in no event will this site or its owners be liable for any losses or damages associated with your use of our site or content. Click here to see our full Disclaimer.

Leave a Comment

*