Get random post in Wordpress - wordpress

How do I get a random post in Wordpress?
I would like to display a button on a page that, when pressed, goes to a random post from the blog. I don't want a random post to be displayed on the page, I just want a link that leads to that post.
I tried searching for a code on Google and here at stackoverflow but no success.
Thanks...
UPDATE:
Here is my template code:
<?php /*Template Name: Random*/ ?>
<?php get_header(); ?>
<nav><?php wp_nav_menu(array('menu' => 'Main Nav Menu')); ?></nav>
<div id="main-content-archive">
<div class="grey-text">Random post</div>
<?php $query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );?>
<?php if (have_posts()) : while ( $the_query->have_posts() ) : $the_query->the_post();
echo '<li>';
the_title();
echo '</li>';
?>
<?php endwhile; ?>
<?php else : ?>
<h2>Not Found</h2>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

create a page template, and use the following code to get a random post:
//Create WordPress Query with 'orderby' set to 'rand' (Random)
$the_query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );
// output the random post
while ( $the_query->have_posts() ) : $the_query->the_post();
echo '<li>';
the_title();
echo '</li>';
endwhile;
// Reset Post Data
wp_reset_postdata();
then in a page, just use:
see a random post

I found this post which gave me desired results...
Here's a solution copy/pasted from the wpbeginner blog post. No copyright infringement intended.
Just add the following code to the functions.php file:
add_action('init','random_add_rewrite');
function random_add_rewrite() {
global $wp;
$wp->add_query_var('random');
add_rewrite_rule('random/?$', 'index.php?random=1', 'top');
}
add_action('template_redirect','random_template');
function random_template() {
if (get_query_var('random') == 1) {
$posts = get_posts('post_type=post&orderby=rand&numberposts=1');
foreach($posts as $post) {
$link = get_permalink($post);
}
wp_redirect($link,307);
exit;
}
}
Use mydomain.com/random/ as your href for your button that leads to the random post.
Thanks everyone who contributed for your help...
Cheers!

I find it is more useful to have a URL that will redirect to a random post that you can use as link in sidebar or in menus. If it is a single WP site and even on wp.com it's really easy, for a blog at
http://mygroovywpsite.me/
All you need to do is append it with ?random
http://mygroovywpsite.me/?random
I found this did not work (nor the wp_beginner code above) on subsites in my multisite installation, either approach just loaded the home page. Maybe I had some funky cache issues. The way I do this on many sites is a few more steps w/o plugins.
First make a Page in your site called "Random" / with the slug "random" -- it does not need any content in it
Then create a page-random.php template
<?php
/*
Random Post Picker
Use on page to send viewer to random post optionally mod query
*/
// set arguments for WP_Query on published posts to get 1 at random
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'orderby' => 'rand'
);
// It's time! Go someplace random
$my_random_post = new WP_Query ( $args );
while ( $my_random_post->have_posts () ) {
$my_random_post->the_post ();
// redirect to the random post
wp_redirect ( get_permalink () );
exit;
}
?>
Then you get the re-direct for any link on your blog ...../random w/o any wrestling with .htaccess
I've done it this way because I've had to modify the query, sometimes for custom post type, sometimes to restrict to category, etc.
I only had one site that was a problem because the hosting suppressed the use of mySQL queries with ORDER BY RAND()

Another Simple solution to display Random Post
1.First a create a custom page template. Name it as random post or a name of your choice!
2.Open the page and remove the default wp loop and Paste the code below
3.To change the no of post change the number ‘1’ to your choice!
<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile;
endif; ?>
source: http://www.yengkokpam.com/displays-random-posts-in-a-page/

Check This
<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><?php the_title(); ?></li>
<?php endforeach; ?>
</ul>

Related

Custom Query breaking WP admin

I have this simple custom query that loops through my custom post type.
It is inside the plugins folder, activated, and is turned into a shortcode, which works perfectly.
The shortcode displays everything like it should. HOWEVER:
When i go to edit the page, I get a quick white page with the query results in it, then the editing admin page opens. And then my admin bar is also completely seperated from the left side.
And then when pressing on "edit", it gives me an error saying "Updating failed. Response is not a valid JSON-response".
This is driving me insane, I have done multiple of these before, but not for some reason my entire admin breaks just from a simple loop. What am i missing?
Thank you for your time!
function show_ambassadors($atts) {
$args = array(
'post_type' => 'ambassadorer',
'post_status' => 'publish',
'posts_per_page' => 8,
'orderby' => 'title',
'order' => 'ASC'
);
$loop = new WP_Query($args);
?>
<div class="ambassador-container">
<?php
if($loop->have_posts()) {
while ( $loop->have_posts() ) : $loop->the_post();
$thumbnail = get_post_thumbnail_id($post);
$image = wp_get_attachment_image_url($thumbnail, "thumbnail");
$categories = get_the_terms( $post->ID, 'category' );
?>
<div class="ambassador-inner-container">
<div class="ambassador-image" style="background-image: url('<?php echo $image ?>'); background-size: cover; background-repeat: no-repeat;"></div>
<h3 class="ambassador-title"><?php print the_title(); ?></h3>
<h4 class="ambassador-category"><?php foreach($categories as $cats) {echo ($cats->name);} ?></h4>
</div>
<?php
endwhile;
}
?>
</div>
<?php
}
add_shortcode('showamb', 'show_ambassadors');
When using the the_post() method of WP_Query, you manipulate global variables that are used by the “main WordPress loop”.
You need to use the wp_reset_postdata function in order to restore those global variables:
if($loop->have_posts()) {
while ( $loop->have_posts() ) : $loop->the_post();
[...]
endwhile;
wp_reset_postdata();
}

Access trashed Wordpress posts on the front-end

I've got this script to list all the post titles with permalinks including posts that are in the trash, on the front-end:
<ul>
<?php
$myposts = get_posts(array(
'numberposts' => -1,
'offset' => 0,
'category' => $cat_id,
'post_status' => array('publish','trash')
)
);
foreach($myposts as $post) :
setup_postdata($post);
?>
<li><?php the_title(); ?></li>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
</ul>
This works fine. But the problem is if I click on any of the post titles that are in the 'trash', I get the 404 page.
How can I access trashed posts on the front-end? I understand this the default Wordpress behaviour, but is there perhaps a function that allows trash posts to be viewed?
Thanks in advance.
By default, only published posts are displayed by the main query for all users and additional private posts for logged in users. So we can use the pre_get_posts hook to add an additional post status to the main query
This is totally untested, not sure it will work, but you can try the following
add_action( 'pre_get_posts', function ( $q )
{
if ( $q->is_main_query()
&& $q->is_single() // can replace with $q->is_singular()
) {
$q->set( 'post_status', array('publish','trash') );
}
});

Wordpress query posts by tag and category

I'm trying to create a set of WP pages with indices to all posts which have tag X as well as category Y.
I found this which seems to do exactly what I want and I understand how to edit it for each index page, but I don't know where/how to use the actual code to create the index pages.
global $wp_query;
$args = array(
'category__and' => 'category',
'tag__in' => 'post_tag', //must use tag id for this field
'posts_per_page' => -1); //get all posts
$posts = get_posts($args);
foreach ($posts as $post) :
//do stuff
endforeach;
TIA for your help.
This is what finally worked - note that I needed the category ID but the tag slug.
<?php if ( have_posts() ) : ?>
<?php query_posts( 'cat=6&tag=a1&&orderby=title&order=asc' );?>
<?php while ( have_posts() ) : the_post();?>
<?php get_template_part( 'content', 'search' ); ?>
<?php endwhile; ?>
<?php else : ?>
You use that code to replace the basic query in the loop in your template.
https://codex.wordpress.org/Function_Reference/query_posts

Get page by id and show read more

What is the best way to show multiple pages in a Wordpress page.
I only want to show the text before the read more. The following code is displaying the whole content instead of only the read more.
$args=array(
'orderby' =>'parent',
'order' =>'asc',
'post_type' =>'page',
'post__in' => array(9,24,33),
);
$page_query = new WP_Query($args); ?>
<?php while ($page_query->have_posts()) : $page_query->the_post(); ?>
<article class="g320">
<?php the_content("Lees meer",true);?>
</article>
<?php endwhile; ?>
There is a global variable $more which enables / disables this feature for the_content() function. Read more in Codex
In your example, the solution would be like this:
$args=array(
'orderby' =>'parent',
'order' =>'asc',
'post_type' =>'page',
'post__in' => array(9,24,33),
);
$page_query = new WP_Query($args); ?>
<?php while ($page_query->have_posts()) : $page_query->the_post(); ?>
<article class="g320">
<?php global $more; $more = 0; ?>
<?php the_content("Lees meer",true);?>
</article>
<?php endwhile; ?>
Currently you are displaying full content using the_content.
But you can display excerpt with [...] at the end of each post.
So change the_content to the_excerpt and check if this fits your needs.
Read more here - http://codex.wordpress.org/Function_Reference/the_excerpt
As you can read in above link "By default, excerpt length is set to 55 words. To change excerpt length using excerpt_length filter, add the following code to functions.php file in your theme:
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Wordpress: A page with random posts

I haven't worked much with wordpress, what I am trying to do is have a page that displays random posts.
It would be similar to my main page where the latest posts are shown but it would display random posts every time the page is refreshed.
If the main page is at http://example.com i want my random page to be at http://example.com/random
how to do it?
The orderby argument to get_posts accepts the value rand.
<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><?php the_title(); ?></li>
<?php endforeach; ?>
</ul>
More info in the documentation: http://codex.wordpress.org/Template_Tags/get_posts#Random_posts
Enable permalinks for you wordpress installation by visiting http://example.com/wp-admin/options-permalink.php, If you would like the title of the post to be the last url segment you would select Custom Structure and set this value to %post_name%
Create a new page template in your current theme folder as described here: Creating Your Own Page Templates
Create a new page witht the title Random and select your newly created page template under Page Attributes in the pages edit screen.
Then in your page template you would do something like this as Filip suggested:
<ul>
<?php
$args = array('posts_per_page' => 5, 'orderby' => 'rand');
$rand_posts = get_posts($args);
foreach ($rand_posts as $post) : ?>
<li><?php the_title(); ?></li>
<?php endforeach; ?>
</ul>
Try This ...
1.First a create a custom page template. Name it as random post or a name of your choice!
2.Open the page and remove the default wp loop and Paste the code below
3.To change the no of post change the number ‘1’ to your choice!
<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile;
endif; ?>
source: http://www.yengkokpam.com/displays-random-posts-in-a-page/
You can use this code to display random posts on your page.
<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile;
endif; ?>

Resources