Add a ‘Surprise Me’ Button Using PHP in WordPress?

By Moe Jame Share
Browse the WordPress category for more tutorials

How to Load Random Articles on Click in WordPress?

First, we need to explain you in brief how WordPress Databases works. You do not even need to login to your MySQL database for this step.

To keep it short, just understand that in your WordPress database, you have a table called WP_POSTS which stores all your posts data, revisions to posts, etc. This tutorial will access this database to do a simple query, which will only show us the actual blog posts, nothing else.

The SQL query is

SELECT * FROM `wp_posts` WHERE post_status = 'publish'

Now that we know the query, we will start the tutorial.

1. Go to the root of your WordPress folder, and create a file, call it surprise.php.

2. Now, we will create a PHP Code to allow us to run the SQL query above. Lets get started:

<?php
$db = dbconn('localhost','database','username','password');

function dbconn($server,$database,$user,$pass){
$db = mysql_connect($server,$user,$pass);
$db_select = mysql_select_db($database,$db);
return $db;
mysql_close($db);
}

$selectrandom = mysql_query("SELECT guid FROM wp_posts WHERE post_status = 'publish' ORDER BY RAND() LIMIT 1");

if (!$selectrandom) { $error = "Unavailable";    } // Give an error.
if (!$error || $error =='') {
while($extract = mysql_fetch_array( $selectrandom )):
$surprisetutorial = $extract['guid'];
$successmessage = "<h1>Surprise Loading...</h1>";
endwhile;
} else { return "Woops, sorry. Something went wrong."; }
?>

Section by section, We first define our database information and credentials (you need to replace the data in orange with your own information. We then connect to the database using the SQL query from above, but with a little twist:

... ORDER BY RAND() LIMIT 1

For those of you who are not familiar with SQL, this is basically running the query to get all articles from our WordPress WP_POSTS database and select them randomly (ORDER BY RAND()) and we only want one article to be selected (LIMIT 1).

3. Now, the code above works perfectly, you can add some basic HTML to redirect to the article by random:

<html>
<head>
<meta http-equiv="refresh" content="2;url=<?php echo $surprisetutorial; ?>">
<title>Surprise Me - Show a random tutorial every time you load this page</title>
<style>
body {
margin:50px 0px; padding:0px;
padding-top: 50px;
background-color: #000000;
}
h1 {
color: #ffffff;
font-family: "Lucida Sans Unicode","Lucida Grande",Garuda,sans-serif;
font-size: 34px;
}
</style>
</head>
<body>
<center>
<img src="https://thinktutorial.com/wp-content/themes/thinktutorial/images/surprise/thinktutorial-large.png">
<br><?php echo $successmessage; ?>
<img src="https://thinktutorial.com/wp-content/themes/thinktutorial/images/surprise/surprise_load.gif">
</center>
</body>
</html>

4. Now, you have a complete code that will randomly point your visitors to a random articles. You can click on the Surprise Me! Button above to test it out.

5. If you are experienced with .htaccess and Mod_Rewrite from Apache, you can add some neat rules to make this url better looking.

Basically from https://thinktutorial.com/surprise.php to https://thinktutorial.com/surprise/

Open .htaccess in your WordPress root folder.

6. Add this line of code at the end of your .htaccess before the </IfModule>

RewriteRule ^surprise/$ /surprise.php [L]

If you see an HTTP 500 Error after adding this line, this means your server did not access this new HTACCESS rule.

You are done!

Complete code in PHP available here to download.

ara descargar.

Keywords

AddButtonPhpSurprise

More WordPress Tutorials

How to Require Users To Login Before Viewing PostRequerendo que Usuários se Conectem antes de Visualizarem PostsRequerir que Usuarios Accedan antes de Visualizar Entradas on WordPress

How to Streaming Movie Kong: Skull Island (2017) on WordPress

How to Add A Read More LinkAdicionando um Link “Leia Mais”Añadir un Vínculo “Sepa Más” on WordPress

How to Add LinkedIn Share ButtonAdicionando um Botão do LinkedInAñadir un Botón de Compartir LinkedIn on WordPress

How to Add Custom Fields AutomaticallyAdicionando Campos Personalizados AutomaticamenteAñadir Campos Personalizados Automáticamente on WordPress

How to Watch Full Movie Streaming And Download Christmas in Homestead (2016) subtitle english on WordPress

How to Automatically replace wordsSubstituindo Palavras AutomaticamenteReemplazar Palabras Automáticamente on WordPress

How to Automatically Resize ImagesRedimensionando Imagens AutomaticamenteRedimensionar Imágenes Automáticamente on WordPress

How to Define Default Size Of Embedded VideoDefinindo Tamanho-Padrão de VídeoDefinir el Tamaño por Defecto de Videos Incorporados on WordPress

How to Add Minimum Word CountAdicionando Contagem Mínima de PalavrasAñadir un Conteo Mínimo de Palabras on WordPress

Follow us on Twitter Subscribe to our Feeds Become a Fan on Facebook

Follow Us

RSS
facebook
twitter

Didn't find your answer?

Post your question on our forum and ask the community!

Ask a question!