RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

Display Random Posts in WordPress

Display Random Posts in WordPress

Not unlike our articles on rendering a list of future WP posts, and another on listing child pages, the shortcode function on this page utilizes WP's wp_query() class to display a list of random posts. Not entirely unlike a scheduled post on displaying a reading list, displaying random posts is another means of converting your readership by displaying additional article content. Additionally, providing access to older content showcases valuable content that would otherwise be buried in obscurity.

The Result

To display 5 random posts (the default number) we'll use the shortcode of [random]. The result is as follows:

While any number of posts greater than 1 is returned in a list, a single post is returned as follows:

Random post from June 15, 2022: One-Click Marketing Campaigns with Yabber’s Solis Module

The purpose of removed formatting is so that the content can be used in one of our text boxes. A sample is as follows:

The textboxes work well in company with single posts because you can return posts relevant to a specific category or tag. For example, to display a random YouTube post (in a YouTube textbox), usage of [bmtextbox type="youtube"][random number="1" tag="69"][/bmtextbox] returns the following (with 69 being the tag ID for 'youtube').

Another example: A random Facebook post.

You might choose to use a random post as a means to suggest a 'recommended' post. Again, by tag, it's likely to be relevant. Shortcode of [bmtextbox type="wordpress"][random number="1" tag="66" text="Recommended article from"][/bmtextbox] returns:

Recommended article from June 28, 2017: Count Facebook Page Likes with WordPress Shortcode or PHP

or...

+ Related WordPress Post

An example list of random posts with excerpts can be found here.

You may optionally return a post by category or author, and you may also include the description (details below).

WordPress Shortcode

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin. You may optionally download and install our plugin from the bottom of of the page.

1
<?php 
2
/*
3
 Display Random Posts in WordPress
4
 http://www.beliefmedia.com/wordpress-random-posts
5
*/
6
 
7
function beliefmedia_random_posts($atts) {
8
 
9
  $atts = shortcode_atts(array(
10
    'status' => 'publish',
11
    'text' => 'Random post from',
12
    'author' => false,
13
    'category' => false,
14
    'tags' => false,
15
    'orderby' => 'rand',
16
    'format' => false, /* jS F Y, g:iA */
17
    'description' => false,
18
    'remove' => false,
19
    'words' => 15,
20
    'number' => 5,
21
    'p' => false,
22
 
23
    /* Style */
24
    'headingstyle' => false,
25
    'datestyle' => false,
26
    'textstyle' => false,
27
 
28
    /* Style */
29
    'cache' => 3600 * 2,
30
 
31
  ), $atts);
32
 
33
 $transient = 'bmrp_' . md5(serialize($atts));
34
 $cachedposts = get_transient($transient);
35
 
36
 if ($cachedposts !== false) {
37
 return $cachedposts;
38
 
39
 } else {
40
 
41
    global $post;
42
 
43
    /* If styles aren't defined */
44
    if ($atts['headingstyle'] === false) $atts['headingstyle'] = 'font-weight: bold;';
45
    if ($atts['datestyle'] === false) $atts['datestyle'] = 'font-size: 0.9em;';
46
    if ($atts['textstyle'] === false) $atts['textstyle'] = 'font-size: 0.9em;';
47
 
48
    /* Generally use this shortcode for random posts */
49
    $post_status = explode(',', $atts['status']);
50
 
51
    $args = array(
52
        'post_type' => 'post',
53
        'post_status' => $post_status,
54
        'orderby' => $atts['orderby'],
55
    );
56
 
57
    /* Limit authors? */
58
    if ($authors !== false) $args['author__in'] = $atts['author'];
59
 
60
    /* Limit number of posts? */
61
    $args['posts_per_page'] = ($atts['number'] !== false) ? $atts['number'] : '-1';
62
 
63
    /* Specific categories? */
64
    if ($atts['category'] !== false) $args['cat'] = $atts['category'];
65
 
66
    /* Specific tags? */
67
    if ($atts['tags'] !== false) $args['tag_id'] = $atts['tags'];
68
 
69
    /* Query */
70
    $pages = new WP_query($args);
71
 
72
    /* Build result */
73
    if ($pages->have_posts()) :
74
 
75
          if ($atts['number'] != '1') {
76
 
77
               $output = '
78
<ul>';
79
 
80
               while ($pages->have_posts()) : $pages->the_post();
81
 
82
                   /* By default your WP time format is used */
83
                   $date = ($atts['format'] !== false) ? get_the_date($format = $atts['format']) : get_the_date();
84
 
85
                   /* If displaying excerpt */
86
                   if ($atts['description'] !== false) $excerpt = trim(str_replace($atts['remove'], '', get_the_excerpt()));
87
 
88
                   if ( ($atts['words'] !== false) && ($atts['description']) ) $excerpt = wp_trim_words($excerpt, $num_words = $atts['words'], $more = null);
89
                   $output .= '
90
<li><span style="' . $atts['headingstyle'] . '"><a href="' . get_permalink() . '" title="' . get_the_title() . '">' . get_the_title() . '</a></span> — <span style="' . $atts['datestyle'] . '">' . $date . '</span>';
91
                   if ($atts['description'] !== false) $output .= '<span style="' . $atts['textstyle'] . '">' . $excerpt  . '</span>';
92
                   $output .= '</li>
93
 
94
';
95
 
96
               endwhile;
97
               $output .= '</ul>
98
 
99
';
100
 
101
          } else {
102
 
103
               while ($pages->have_posts()) : $pages->the_post();
104
                   $output = trim($atts['text']) . ' ' . $date = ($atts['format'] !== false) ? get_the_date($format = $atts['format']) : get_the_date() . ': <strong><a href="' . get_permalink() . '" title="' . get_the_title() . '">' . get_the_title() . '</a></strong>';
105
                   if ($atts['p'] !== false) $output = '' . $output . '';
106
               endwhile;
107
          }
108
 
109
    else :
110
 
111
        $output = '
112
<ul>
113
<li>No posts to show.</li>
114
</ul>
115
 
116
';
117
 
118
    endif;
119
 
120
   /* Set transient data */
121
   set_transient($transient, $output, $atts['cache']);
122
   return $output;
123
 
124
   /* Reset query */
125
   wp_reset_postdata();
126
 
127
   }
128
 
129
}
130
add_shortcode('random', 'beliefmedia_random_posts');

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

Shortcode Attributes

The following list of attributes will alter the behaviour of your list.

text

For single post, the text is rendered before the data.

author

To return random posts by specific authors, include their IDs.

category

To return random posts by category, include the category ID(s).

tags

To return random posts by tag (as demonstrated above), include the tag ID(s).

description

To include the post excerpt, use description="1"

remove

To remove a specific string of text from the excerpt (handy if you add content to the post), use remove="your text here".

words

The words attribute is the number of words to include in your excerpt.

number

The number of posts to return. If more than one post is required, they'll be returned in a list.

p

The p attribute is for single random posts. If you're including the text inline, use default (false). Otherwise, use p="1". This overcomes issues with shortcodes and paragraph breaks.

headingstyle

Default heading style is font-weight: bold;. Alter as required.

datestyle

Default date style is font-size: 0.9em;. Alter as required.

textstyle

Default excerpt text style is font-size: 0.9em;. Alter as required.

cache

To avoid costly requests to the WP database, we cache results for 2 hours by default.

Considerations

  • The function can return posts of any type in an order. However, for the purpose of simplicity we make shortcodes available for each task.

Download

Recommended: Text Boxes With WordPress Shortcode.


Title: BeliefMedia Random Posts (WP Plugin)
Description: Display random posts in WordPress with shortcode.
  Download • Version 0.2, 2.1K, zip, Category: WordPress Plugins (General)
WordPress Shortcodes, (1.4K)    

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment