How to build a custom widget to display trending posts on your blog

A trending-post widget gives popular articles a visible place on your homepage, sidebar, or article pages. Instead of relying on a generic “latest posts” list, it highlights content that is attracting genuine attention, helping visitors discover useful guides and encouraging them to spend longer on your site.

For a WordPress blog, the process involves choosing a reliable popularity signal, storing or retrieving that data, creating a secure query, and presenting the results in a compact design. A well-built widget should load quickly on mobile, support search visibility, and remain useful for readers in different locations, including visitors browsing from Sydney, Melbourne, Brisbane, or regional Australia.

Choose a useful definition of trending

“Trending” can mean several things. You might rank posts by page views during the last seven days, recent shares, comments, newsletter clicks, or a blended score. Page views are usually the easiest metric to collect, but raw lifetime views can cause old articles to dominate forever. A rolling time window produces a fresher list.

For a business or technology blog, a simple scoring model works well. For example, assign one point for a page view, three points for a social share, and five points for a comment during the past week. If you do not have access to every signal, use a custom field such as views_7d. The important point is to define the measurement period clearly and update it regularly.

Your list should also include editorial safeguards. Exclude private posts, sponsored content that should not appear organically, outdated announcements, and articles with broken links. A tutorial about setting up a VTU website may remain popular for months, while a time-sensitive guide about pricing or legislation could become misleading quickly.

Prepare the WordPress data layer

You can store popularity information in post metadata, a dedicated database table, or an analytics service. Post metadata is suitable for a small or medium blog because it is easy to query through WordPress. Add a field such as views_7d to each post and update it through a controlled server-side process.

Avoid increasing the counter every time an administrator reloads a page or a bot scans the site. Exclude logged-in users, known crawlers, and repeated requests from the same visitor within a short period. A lightweight cookie or a hashed, short-lived visitor identifier can reduce inflated figures. If your system tracks identifiable behaviour, review the Privacy Act 1988 and the Australian Privacy Principles before collecting or retaining that information.

The following shortcode creates a reusable content block. It orders posts numerically by the weekly view value, escapes the title and URL, and adds a class that can be styled later:

function vtu_trending_posts_widget() {
    $posts = get_posts([
        'post_type'      => 'post',
        'posts_per_page' => 5,
        'post_status'    => 'publish',
        'meta_key'       => 'views_7d',
        'orderby'        => 'meta_value_num',
        'order'          => 'DESC',
        'no_found_rows'  => true,
    ]);

    if (!$posts) {
        return '<p class="trending-empty">No trending posts yet.</p>';
    }

    $html = '<section class="trending-widget" aria-labelledby="trending-title">';
    $html .= '<h2 id="trending-title">Trending now</h2><ol>';

    foreach ($posts as $post) {
        $html .= '<li><a href="' . esc_url(get_permalink($post)) . '">'
              . esc_html(get_the_title($post)) . '</a></li>';
    }

    $html .= '</ol></section>';
    return $html;
}
add_shortcode('trending_posts', 'vtu_trending_posts_widget');

Place this code in a small custom plugin rather than directly in a theme file. A plugin keeps the widget working when you change themes. You can then insert [trending_posts] into a page, widget area, block, or template location supported by your theme.

Build the display and interaction

The widget should be visually clear without competing with the main article. A numbered list is often better than a collection of large thumbnails because it takes less space and creates a natural ranking. Use a short title, readable contrast, generous line height, and a visible hover and keyboard-focus state.

A simple stylesheet could use the following rules:

.trending-widget {
    padding: 1rem;
    border: 1px solid #e5e7eb;
    border-radius: 10px;
    background: #fff;
}

.trending-widget h2 {
    margin-top: 0;
    font-size: 1.2rem;
}

.trending-widget ol {
    margin: 0;
    padding-left: 1.5rem;
}

.trending-widget li {
    margin: .7rem 0;
}

.trending-widget a {
    color: #123b68;
    text-decoration: none;
}

.trending-widget a:hover,
.trending-widget a:focus {
    text-decoration: underline;
}

Keep the markup semantic. The section, h2, and ordered list help screen-reader users understand the component. Do not depend on colour alone to show links or ranking. If you include thumbnails, add meaningful alternative text and set fixed image dimensions so the page does not jump while loading.

On Australian websites, mobile performance deserves particular attention because readers may move between home Wi-Fi, office networks, and mobile data during the day. A compact text widget can serve visitors efficiently, while responsive CSS can place it below the article on narrow screens and in a sidebar on desktop layouts.

Improve speed, accuracy, and search value

A dynamic query on every page view can add database work, especially when your homepage receives traffic from several campaigns at once. Cache the rendered widget with a WordPress transient for five to fifteen minutes. This keeps the ranking reasonably fresh without running the same query for every visitor.

You can also generate a daily or hourly ranking with a scheduled task. The task calculates scores, writes the top post IDs to an option, and allows the front end to retrieve a small, predictable dataset. If you use an external analytics platform, avoid exposing private reporting credentials in JavaScript. Send only the final approved results to the browser.

Trending links can support internal linking, but they should not replace descriptive navigation. Use meaningful article titles rather than vague labels such as “Read this” or “Click here”. Add a short introductory sentence where appropriate, and make sure the linked articles have a useful meta title, summary, canonical URL, and updated publication date.

Test the widget with cache plugins, content delivery networks, and common page builders. Confirm that it remains correct when a post is unpublished, a title contains special characters, or a URL includes query parameters. Also test keyboard navigation, screen magnification, Safari on iPhone, Chrome on Android, and slower connections.

Keep the ranking trustworthy and commercially useful

Readers notice when a “trending” list repeatedly promotes one advertiser or an old article with artificially high traffic. Publish a clear internal rule for ranking and review unusual spikes. A sudden increase from a bot network, paid campaign, or referral spam should not automatically determine what every visitor sees.

If you work with agencies, freelancers, or overseas developers, keep contracts, invoices, access records, and delivery notes together. When a supplier fails to complete agreed work, a formal reminder template may help organise a written demand, although Australian legal advice is appropriate before relying on a foreign legal format or claiming a penalty.

Australian compliance should form part of the design process. If the widget relies on analytics cookies, explain the collection practice in your privacy policy and check whether consent or additional disclosure is needed. If the list is used to support email promotions, review the Spam Act 2003 and include a working unsubscribe process. For a local audience, showing dates and time-sensitive labels in Australian Eastern or relevant local time can prevent confusion around launches and promotions.

The widget can also support revenue without becoming intrusive. Place a relevant service article near a guide about website setup, or connect a popular SEO tutorial to a course or digital product. If a link is paid, sponsored, or affiliate-based, disclose that relationship clearly. Australian readers generally respond better to useful recommendations than aggressive pop-ups and cluttered sidebars.

Track results after launch. Compare widget clicks, pages per session, scroll depth, return visits, and conversions against a period when the widget was absent. Review the list every few weeks to remove stale content and check whether visitors from cities such as Perth or Adelaide behave differently from users in Sydney and Melbourne. These insights can help you adjust the scoring window, placement, and article mix.

Start with the shortcode, a dependable weekly metric, and a lightweight design. Add caching and editorial checks before expanding the system with social signals or personalised rankings. Once the widget consistently surfaces useful content, place it across your highest-traffic templates and use its performance data to improve the wider content strategy.