Create a random post button for WordPress

If you like to get more page views per visitor on your WordPress site or blog you should try a random post button. People like to get surprised on what the next page will show them. The whole idea of StumbleUpon is based on random web pages, every time you click their stumble button you get a new random article, image or video.

The following code will select a random article and shows the link together with a graphical button on your site.

If you “echo” the function somewhere in your theme, a random post link will show up with your button. Note the number “1000” used inside the function “wp_get_attachment_url()”, this is the ID from the image used as your button.

Create a WordPress shortcode

A much better concept would be by using a shortcode in your article, theme or widget. Use this code to create a shortcode instead:

Now you can use this shortcode in your article or post:

If you like to use this short code inside the text widget you need to add this filter into your functions.php file too:

Tip! Experiment with different positions, button text and colors and if you like share your results here.

10 Responses

  1. Where exactly do I copy the code into if I want the random button to be shown on my Homepage?

    Thx for now


  2. Thx for responding Olav, but I already know that you can choose in which part of a site you can copy it. In my case I would like it to appear in the sidebar, so I will have to insert the code in sidebar.php, I suppose. What I’m looking for is where exactly within the code within sidebar.php I have to drop it. I tried doing this but if I drop it at random within the code, all I get is the text of the script appearing on my site within the sidebar which is of course not the intention.
    For other items I already found pieces of script AND their exact location within php where to drop it. Only for the randombutton I only seem to find the script and not any details on where to drop it within the phpscript. I’m pretty new to this stuff so forgive me if I’m perhaps not on edge.

  3. Sorry Olaf, but it’s not getting any clearer this way. I don’t understand where this is all getting to, be a bit more precise please. I just want to know after which line of code (and before which other line of code) within the sidebar.php I have to drop the piece of scrpit. In other words just till me the exact location in sidebar.php I have to insert the code to get the randombutton up and running.
    I don’t trust external stuff like pastebin and such, I only want to make adjustments to my site from within my own editor
    Still, thx you for trying to help me.

    1. :)
      don’t put secret code into the theme files!
      there is no exact location for the code snippet, you can send me the file if you like.

  4. I work with the Twenty Eleven Theme and there is no sitemap.php under the editor.

Comments are closed.