Random post in WordPress without plugins

0

Like on my blog: if you go to http://blog.dexterxx.pl/random (or click „random” in menu) it will redirect you to random post on my blog – how I did that without plugins on WordPress?

Easily!

Create page template

Open any developers editor, paste code below, save it named eg. „single-random.php”.

<?php
/*
Template Name: Random post
*/

$args = array( 'numberposts' => 1, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post )
{
if (($link = get_permalink()) === false)
die('something fucked up ;-) ');
else
wp_redirect( $link , 303 );

exit;
}

Put file in your template folder on server

Example: /blog/wp-content/themes/my_theme/

Create new page using template

Go to sites, add new. Name it as you want (in my case: random). Set url which you want.

Content leave blank, on right side select our „Random post” template.

Publish, test, all done!

Tagi: ,

Skomentuj