Skip to content

Instantly share code, notes, and snippets.

@andornagy
Created April 22, 2014 13:02
Show Gist options
  • Save andornagy/11178314 to your computer and use it in GitHub Desktop.
Save andornagy/11178314 to your computer and use it in GitHub Desktop.
<?php
function random_post() {
global $wpdb;
$arr = $wpdb->get_results("SELECT ID FROM wp_posts WHERE post_type='post' and post_status='publish'
","ARRAY_A");
$curr_id = get_the_ID();
$numbr = array_rand($arr);
if($arr[$numbr][ID] == $curr_id){
$numbr = array_rand($arr);
}
$new_id = $arr[$numbr][ID];
$postlink = get_permalink($new_id);
return "<a href='" . $postlink . "' title='" . get_the_title($new_id) . "'>Random Post</a>";
}
<?php
add_filter('wp_nav_menu_items','add_custom_in_menu', 10, 2);
function add_custom_in_menu( $items, $args ) {
// Don't forget to chnage "primary-menu" to the ID of your navigation menu
if( $args->theme_location == 'primary-menu') {
$items .= '<li>' . random_post() . '</li>';
}
return $items;
}
<!-- The code below will generate a list of 5 random posts -->
<li><h2>Random Post</h2>
<ul>
<?php $posts = get_posts('orderby=rand&numberposts=5'); foreach($posts as $post) { ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php } ?>
</ul>
</li>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment