If you check the side bar on this site you’ll find a “feeling lucky” button. This is inspired by Google’s feeling lucky button.Although it works a little but differently than google’s button . This button will take you to a random post .This is a great way to show your visitors your old posts .
1- The theme page
I’ve used here one of my favorite word press features which is page templates . I created a new theme file called lucky.php
Add this code
1 2 3 4 5 6 7 8 9 | <?php /* Template Name: lucky */ query_posts('showposts=1&amp;orderby=rand'); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> < ? header('Location: '.get_permalink()); ?> |
make sure you keep the comment “template name:lucky ” as this is important for wordpress to detect the file later.
This is just like any other file in wordpress theme that displays a post (eg: single ) . The difference here is that we’ve used the function query_post
1 | query_posts('showposts=1&orderby=rand'); |
to retrieve one post only in random (rand) order.then start the loop.Inside the loop instead of display the post we redirect the user to the post’s page using
1 |
2- Create the page
Create a new page .From Templates list choose your template in this case “lucky”.If you for some reason can’t find your template in the list make sure you didn’t remove the comment from the file above. save your page ..
now your lucky url will be http://yourdomain.com/lucky
lucky02
3-Create your button
Add your button to your template. In our sites case I’ve added it to my sidebar.php
1 | <a id="lucky" href="./lucky">Feeling lucky </a> |
That’s it hope you find it useful .
81 Inspiring Sketchs from Flickr
This is really, really cool! I’ve never seen anything like this, so this is an awesome unique tutorial to add to any WordPress blog.
Sorry for commenting OT – what Word Press template are you using? It’s looking cool!
looks good, well done