WordPress Random Post Button Code Snippets

People love hitting those random posts. What better way is there to keep people on a website than by giving them a random post button to push. Pushing that button is like pulling a leaver on a slot machine: ya never know when you’re going to hit Jackpot. Add a random post button to your menu or random post buttons to your posts and sidebars with a couple of easy to use copy and paste code snippets.

In this How-To guide you see

  1. How to make a random post button shortcode
  2. How to add a random post button to your nav menu

We will keep the code and instructions simple. Read the notes in the code.

This method creates a button that links to a random post on each press. The target page uses the actual URL of the page. Other methods use a permalink rewrite that adjusts the URL of the randomly chosen page to include a virtual ‘random’ directory in the URL slug e.g. example.com/random/page/, which creates duplicate page content issues. That is bad for SEO. The method shown here at JournalXtra does not use URL rewrites and does not use a random post page template.

The JournalXtra method is SEO standards compatible.

Instructions for using the code

Add the code to your WordPress theme’s functions.php file or install a functionality plugin and add the code snippets to the configuration page of the plugin.

Code added to the functions.php file of a theme will stop working if the theme is deactivated. Code added to a functionality plugin will remain active for as long as the functionality plugin is active and for as long the code is valid.

Part 1: Generate the link to a random post

This code generates the URL to a random WordPress post.

Add this code to your functions.php file or functionality plugin then use one or both of the snippets below this code to add a nav menu button that loads a random page when pressed or to use a shortcode to display a ‘random post’ button in posts and widget areas.

<?php // Remove this line from pasted code. Copy and paste everything below this line.

/**
*	Part 1: Get a link to a random post
**/

/**
*	Random Post Function
*
*	<?php vr_random_post_function() ?>
*	See journalxtra.com
*
**/

function vr_random_post_function( $title='Random Post' ) {
	// Get the URL of a random post and format it as a clickable link
	$posts = get_posts('post_type=post&orderby=rand&numberposts=1');
	foreach($posts as $post) {
		$link = '<a href="' . esc_url( get_permalink($post) ) . '" title="' . $title . '">'.$title.'</a>';
	}
	// Return the link to wherever this function is called
	return $link;
}

Part 2: Random post button for menu bars

This code adds a random post button to the end of the primary navigation menu. The title of the menu tab is ‘Random Post’. Change the title by editing ‘Random Post’ in vr_random_post_function ( ‘ Random Post’ ). The menu bar the button is added to can be changed by editing the ‘if’ statement.

<?php // Remove this line from pasted code. Copy and paste everything below this line.

/**
*	Part 2: Add the link to the random post to a menu (primary menu in this case)
*	https://journalxtra.com
**/

/* Add the random post link to a menu */

add_filter( 'wp_nav_menu_items', 'theme_menu_extras', 10, 2 );
/**
 * Filter menu items and append the random link.
 *
 * @param string   $menu HTML string of list items.
 * @param stdClass $args Menu arguments.
 *
 * @return string Amended HTML string of list items.
 */

function theme_menu_extras( $menu, $args ) {
	// Change 'primary' to 'secondary' to add the random post button to the secondary navigation menu
	if ( 'primary' !== $args->theme_location )
		return $menu;

	$menu  .= '<li class="random-post">' . vr_random_post_function( 'Random Post' ) . '</li>';
	return $menu;
}

Part 3: Random post button shortcode

This code creates a WordPress shortcode that shows a button with the title ‘Random Post’. Each press of the button opens a random post link. Use the shortcode wherever you want a random post button to display.

<?php // Remove this line from pasted code. Copy and paste everything below this line.

/**
*	Part 3: Random post button shortcode
*	https://journalxtra.com
*	
*	[vr-random-post-button]
*
**/

function vr_random_post_button_shortcode() {
	$content = '<div class="vr-random-post button">' . vr_random_post_function( 'Random Post' ) . '</div>';
	return $content;
}
// Add the shortcode
add_shortcode('vr-random-post-button','vr_random_post_button_shortcode');

// The shortcode is [vr-random-post-button]

Style the buttons

Use CSS to style the buttons.

The random post menu button has the CSS class ‘random-post’. The button generated by the shortcode has the CSS classes ‘vr-random-post’ and ‘button’. Some themes include CSS styles for .button{} which is the reason the button class is used.

.vr-random-post {
    display: inline-block;
}

.vr-random-post a {
    display: inline-block;
    color:#000;
    background-color: #FF3112;
    border: 2px solid #000;
    padding: 10px 12px;
}

.vr-random-post a:hover {
    text-decoration: none;
    display: inline-block;
    color:#333;
    background-color: #FF3112;
    border-color: #333;
}

Caveats

The random page button(s) gets cached by WordPress cache plugins and web browsers. Each page of your website will show a different link to a random page but the link shown on a specific page will refresh only when the site cache is refreshed. I will share a cache-buster workaround in a future post.

Over to you!

Leave comments and tips with the discussion form below.

Sharing is caring!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of