How much does a website cost in 2026? Prices and comparison
Showcase site, e-commerce, custom build: how much should you budget for a website in 2026? Detailed prices, a comparison…
ReadA simple function to fetch 10 random posts in WordPress
Let's create a function and add it to functions.php
Let's create an array named $args and add the arguments to it.
The post_type can be a post, a page or any other custom post type.
The orderby argument matters because it sets the order we want, here random.
orderby can also be title, name, ID, slug, etc.
With the posts_per_page argument, you decide how many posts you want to fetch.
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 10,
);
...
Let's create a wp_query instance and pass $args to it
...
$query = new WP_Query( $args );
...
Let's check whether the $query variable contains any posts and, if so, store them with some HTML markup in a PHP string.
We'll also add an else branch for when there are no posts to fetch. In that case, we can simply display a message saying there are no posts to show.
...
if ( $query->have_posts() ) {
$rand_posts .= '<section>';
while ( $query->have_posts() ) {
$query->the_post();
$rand_posts .= '<a href="'. get_permalink() .'">'. get_the_title() .'</a>';
}
$rand_posts .= '</section>';
wp_reset_postdata();
} else {
$rand_posts .= '<p>Pas d\'articles</p>';
}
...
Note that wp_reset_postdata() is inside the if condition.
After the loop, we need to call wp_reset_postdata() to restore the global $post to the current post of the main query.
The final code
function my_random_posts() {
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 10,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
$rand_posts .= '<section>';
while ( $query->have_posts() ) {
$query->the_post();
$rand_posts .= '<a href="'. get_permalink() .'">'. get_the_title() .'</a>';
}
$rand_posts .= '</section>';
wp_reset_postdata();
} else {
$rand_posts .= '<p>Nothing to show</p>';
}
return $rand_posts;
}
add_shortcode('my-random-posts','my_random_posts');
add_filter('widget_text', 'do_shortcode');
You can simply call the function above with the shortcode, and it will display 10 random posts.
With do_shortcode, you can run the shortcode inside a widget.
Website design, e-commerce or SEO: our web agency in Paris, Besançon and Normandy can help.
Free quoteShowcase site, e-commerce, custom build: how much should you budget for a website in 2026? Detailed prices, a comparison…
ReadStruggling to type an accented capital letter on Windows? Here is a complete guide to the Alt code shortcuts.…
ReadContext: we want to underline a text below the text. Modern CSS properties will help us: text-decoration-line: un…
Read