Display random articles in WordPress

You don’t need a plug-in to generate the output of random articles in WordPress. A little php code is all you need.

While searching for the possibility of displaying random articles in the sidebar, for example, I came across a few pages that offered various code snippets for this. Unfortunately, the output did not look good. They simply displayed the article titles as bullet points.


That must work better, nicer. I wanted to change the code. But I really didn’t feel like reading up on the subject. So I asked Gemini if he could help me. He could to a certain extent, but he failed to put a dividing line between the articles.

So I gave the code to ChatGPT, which inserted a separator without any problems. I just had to ask him to leave out the separator under the last article.


External PHP code should be as secure as possible. How can I check that? I asked Gemini and he said that the code could be improved:

The code you showed has no obvious security risks. It uses standard WordPress functions and practices to display articles and insert separators.

Potential risks:

  • Unsecured query parameters: The query $query = new WP_Query('showposts=5&orderby=rand'); does not use an explicit escaping function for the parameters showposts and orderby.
    • Theoretically, an attacker could manipulate these parameters to execute malicious code.
    • However, this is unlikely to be a problem in this case as the parameters do not contain any sensitive data and the query only uses internal WordPress functions.
  • Unsecured image source: The wp_get_attachment_image_src() function retrieves the URL of the post image from the database.
    • If the code is used on a website with user uploads of images, an attacker could upload manipulated images that contain malicious code.
    • However, it is important to note that WordPress scans image uploads by default and blocks potential threats.


  • To increase security, you can escape the query parameters using the esc_attr() function before they are passed into the query.
  • If you allow user uploads of images, you should use a security plugin such as „Wordfence“ or „Sucuri“ to protect your website from malicious code.

In general:

  • Always keep WordPress and your plugins up to date to close security gaps.
  • Use strong passwords for your WordPress installation and database.
  • Create regular backups of your website.


The code does not pose a major security risk if used properly. However, following the above recommendations can help to improve the security of your website.

Well, you have to pull everything out of an AI’s nose, don’t you? What does that mean? „Not a big security risk?“. I don’t want a small security risk either! So I asked for the suggested improvements and gave the code to ChatGPT for review. The colleague actually had some suggestions for improvement:

The code looks good! You have taken some security precautions to minimise potential security risks. Here are some points that you have already taken into account:

  1. Using esc_attr() on $showposts and $orderby to sanitise the input values and make sure they only contain alphanumeric characters and some special characters.
  2. Using esc_url() for the image URL to make sure it is valid and contains only allowed characters.
  3. Using wp_reset_postdata() at the end of the loop to ensure that the global post data is reset and that there are no conflicts with other queries.

Another improvement you could make is to use esc_html() or esc_textarea() for the title and excerpts when outputting them directly in the HTML to ensure that potentially dangerous code is cleaned up in these areas.

Otherwise, the code seems to be well protected and should be safe as long as the functions you use are applied correctly.

I asked for the changes and tested the code on the website. This also worked perfectly.


Gemini has problems producing decent output, at least in direct comparison with ChatGPT. But he is good at analysing, so I asked him to check the code improved by ChatGPT for security problems.

The code you’ve shown is significantly more secure than the previous one, as it implements important measures to defend against potential security risks. Here is a breakdown of the security improvements:

  1. Escaped Query Parameters:

    • $showposts = esc_attr(5); and $orderby = esc_attr('rand');
      • These lines use esc_attr() to escape the query parameters showposts and orderby.
      • This neutralises potentially harmful characters that could otherwise be used to manipulate the query.
  2. Escaped and Sanitised Title:

    • $title = esc_html(get_the_title());
      • This line escapes and sanitises the title of the post with esc_html().
      • This prevents the execution of malicious code that may be stored in the title.
  3. Sanitised Image URL:

    • $sanitised_image_url = esc_url($image_url[0]);
      • This line sanitises the image URL with esc_url() before it is used in the src attribute of the image tag.
      • This ensures that the URL is trustworthy and does not refer to malicious sources.


By implementing these security measures, the code is more resistant to attacks aimed at manipulating data or injecting malicious code.

Further optimisation options (optional):

  • Validation of user uploads: If your website allows users to upload images, you should use a plugin such as „WP-File-Upload“ or „ImageMagick“ to validate the type, size and dimensions of uploaded images. This can prevent potential security vulnerabilities caused by manipulated images.
  • Regular updates: Always keep WordPress, themes and plugins up to date to benefit from security patches.
  • Strong passwords and backups: Use strong passwords and consider two-factor authentication for added security. Perform regular backups of your website.

Although the code presented is already well secured, these additional measures can further enhance the security of your website. Remember that security is an ongoing process. Stay vigilant and keep your website up to date.

Only I can make uploads, the website is constantly updated and secured externally, my passwords are very complex and I have also set up a 2FA. According to human … artificial judgement, I’m on the safe side with this code.

And the alternative? Installing plug-ins for WordPress that come from completely unknown developers and are orders of magnitude more complex than this small piece of code.

The risk?

PHP code runs directly on the server and not in the browser. The user never sees it. By publishing the code that I use on this website, there is a theoretical possibility that an attacker could still discover and exploit a vulnerability in this code. But I can live with that.

PHP code

The code even has explanatory comments and is so readable that I was able to make further changes by hand. The length of the text excerpt, for example.

I then inserted this code into the sidebar using my existing PHP plug-in:

$showposts = esc_attr(5); // Escape query parameter
$orderby = esc_attr('rand'); // Escape query parameter

$query = new WP_Query("showposts=$showposts&orderby=$orderby");
$total_posts = $query->post_count;
$count = 0;

while ($query->have_posts()) : $query->the_post();
  <div class="article-item">
    // Escape and sanitize title
    $title = esc_html(get_the_title());
    // Check if post has thumbnail
    if (has_post_thumbnail()) {
      $image_id = get_post_thumbnail_id();
      $image_url = wp_get_attachment_image_src($image_id, 'large'); // Replace 'large' with desired size
      // Sanitize image URL before using it in the src attribute
      $sanitized_image_url = esc_url($image_url[0]);
      <a href="<?php the_permalink(); ?>">
        <h3><?php echo $title; ?></h3>
        <img src="<?php echo $sanitized_image_url; ?>" alt="<?php the_title_attribute(); ?>">
    <?php } else { ?>
      <a href="<?php the_permalink(); ?>">
        <h3><?php echo $title; ?></h3>
    <?php } ?>
    <p><?php echo esc_html(wp_trim_words(get_the_excerpt(), 20, '...')); ?></p>
  // Add the separator line if it's not the last post
  if ($count < $total_posts) {
    echo '<hr>';

wp_reset_postdata(); // Reset query data


PHP-Code einfügen
Insert PHP code
Seitenleiste, Widget
Sidebar, widget


Of course, I have inserted the article images in the size „Medium“ for the sidebar. Embedded in this article, „Large“ would look much better.

Reload the page and you will see other articles.

This is what it will look like:


I asked Gemini to explain the code. His output is this:

The code shown is a snippet from a WordPress theme and represents a loop that displays random articles. Here is a step-by-step explanation:

1. Query and counter:

  • $query = new WP_Query('showposts=5&orderby=rand');: This line creates a new WordPress query that randomly retrieves 5 posts (showposts=5) from the database and sorts them by random order (orderby=rand).
  • $total_posts = $query->post_count;: Stores the total number of posts retrieved in the variable $total_posts.
  • $count = 0;: Initialises a counter $count to 0 to track the current position within the loop.

2. Loop and article display

  • while ($query->have_posts()): $query->the_post();: This loop runs through each of the retrieved posts.
    • $query->have_posts(): Checks if there are any other posts in the query.
    • $query->the_post();: Sets up the global WordPress environment for the current post so that functions such as the_title() can access its data.
  • Within the loop, the content of each article is displayed in a div element with the article-item class:
    • The title(


      is output.

    • The post image(<?php the_title_attribute(); ?>) is retrieved using the get_post_thumbnail_id() and wp_get_attachment_image_src() functions and displayed at the desired size (medium in this example).
    • The excerpt() is shortened to a maximum of 20 words using the wp_trim_words() function and supplemented with a „…“.

3. Insert separator line

  • if ($count < $total_posts) {: This condition checks whether the current counter ($count) is smaller than the total number of posts ($total_posts).
    • If the condition is true, this means that it is not the last article.
    • Within the if statement, the code then simply inserts an


      to create a horizontal separator between the articles.

4. Exit loop and reset

  • endwhile;: Ends the loop after all posts have been run through.
  • wp_reset_postdata();: Resets the global WordPress environment after the query so that subsequent queries are not affected.


This code displays random articles with title, post image and excerpt in an appealing format and optionally inserts separators between the articles. You can customise the functionality by changing the query parameters (number of articles, sorting) or replacing the separators with images.

My opinion

It’s great that it’s now possible for full-blooded people like me, who spent days and weeks writing the purchasing power calculator, to have simple scripts created by an AI. It’s wonderful that I can get the AI to optimise the code more and more just by describing my needs until it meets my requirements.

Schreibe einen Kommentar

Ich bin mit der Datenschutzerklärung und der Speicherung meiner eingegebenen Daten einverstanden.