Skip to content

Creating a basic widget for WordPress website

In this post, I’ll be walking you through the process of creating a basic widget for WordPress website for a beginner WordPress developer.

This widget displays a random images from a random post and has a link back to the post.

A widget is a small block that performs a specific function and can be placed in a sidebar or other widget-ready area of your WordPress site. Widgets are a simple and easy way to add functionality to your website without having to dig very deep into the code.

You can see this widget on the right of this paragraph.

Prerequisites

  • WordPress website
  • Basic knowledge of programming (PHP)

Requirements

For this project, we need to create a sidebar widget that displays a randomly selected image from a gallery of a randomly chosen post within a specified category. The widget should be displayed as a link containing both the image and the title of the post.

Implementation

The widget requires some code to be executed. One way of doing it is to go into the theme files and add some code there, but it’s not safe, there is a relatively high chance of breaking something. So, I’ll be using a plugin which allows some code snippets to be run. The plugin is called Code Snippets. Let’s install it and activate it.

Inside the plugin, create a new PHP snippet and copy the code from this GitHub file and save.

Now, open Appearance and then Widgets. Pick the Sidebar widget and add an element of type “Shortcode”. Write [random-post-image] inside. This will reference the shortcode we’ve created before.

Implementation details

Picking up a random post

$args = array(
    'post_type' => 'post',
    'orderby' => 'rand',
    'posts_per_page' => 1,
    'category_name' => 'cat2'
);

$the_query = new WP_Query($args);

In the current implementation, the category for picking up a random image is hardcoded to “cat2”.

Selecting a random image

In order to get a random image from the selected post, we need to go over all galley elements and collect all image Ids to the array. Then pick a random element and get an image with this id from the database.

if (has_block('gallery', $post->post_content)) {
    $post_blocks = parse_blocks($post->post_content);
    $ids = [];
    foreach ($post_blocks as $block) {
        if ('core/gallery' === $block['blockName']) {

            foreach ($block["innerBlocks"] as $image) {
                if ('core/image' === $image['blockName']) {
                    array_push($ids, $image['attrs']['id']);
                }
            }
        }
    }
    $rnd_image_id = $ids[array_rand($ids)];
}

Create a link from the image and its post

$string = '<h3>Random post</h3>';
$string .= '<a href="' . get_permalink() . '">'
    . wp_get_attachment_image($rnd_image_id, '100%')
    . '<br/>'
    . get_the_title()
    . '</a></li>';
$string .= '</ul>';

Troubleshooting

Caching

Problem: A random image is generated once per post and regenerated only when a new post is created

Solution: Disable caching for the posts you want to show random images. This is not a very efficient solution, but it’s the nature of the requirements: generate something new every time.

An alternative solution can be using only a front-end approach, where the random image in the sidebar is changed only on the UI, but not generated in WordPress (PHP)