5 Code Snippets Every Developer Needs in November 2026 (WordPress, Laravel & Python)

Five copy-paste snippets with full code: limit WordPress revisions, add reading time, log slow Laravel queries, organize Downloads and bulk-convert images to WebP.

AD Admin PenduCoder 8 min read
5 Code Snippets Every Developer Needs in November 2026 (WordPress, Laravel & Python)
On this page

A good snippet is a small piece of code that solves one annoying problem for good. Below are five we keep coming back to on real projects in late 2026 — two for WordPress, one for Laravel and two for Python. Each one comes with the full code, where to put it, how it works and the mistakes to avoid, so you can paste it today and understand it tomorrow.

Every snippet also has its own page in our snippets library with a one-click copy button.

Why these five?

Three problems show up again and again in client work: databases that quietly bloat, pages that are slow for reasons nobody can find, and repetitive file chores that eat an hour every week. These five snippets attack exactly those problems with minimal code and no extra plugins or paid tools.

1. Limit WordPress post revisions and slow down autosave

WordPress stores a full copy of your post every time you save. A blog with 500 posts edited 30 times each carries 15,000 revision rows in wp_posts — slower backups, slower queries, bigger database. Two constants fix it.

// wp-config.php — add ABOVE the line "That's all, stop editing!"
define( 'WP_POST_REVISIONS', 5 );   // keep only the last 5 revisions per post
define( 'AUTOSAVE_INTERVAL', 120 ); // autosave every 120 seconds instead of 60

Want different limits for different post types? Use the filter instead, in your theme's functions.php or a small custom plugin:

add_filter( 'wp_revisions_to_keep', function ( $num, $post ) {
    if ( 'page' === $post->post_type ) {
        return 10;  // pages change rarely, keep more history
    }
    return 5;
}, 10, 2 );

Clean up old revisions that already exist (back up your database first). With WP-CLI:

wp post delete $(wp post list --post_type=revision --format=ids) --force

Watch out: the constant only affects future saves — it does not delete existing revisions. And defining it after the require_once ABSPATH . 'wp-settings.php' line has no effect. Full version: Limit WordPress post revisions and autosave.

2. Show estimated reading time on WordPress posts

A "4 min read" label sets expectations and measurably helps readers decide to start a long article. No plugin needed:

// functions.php
function pc_reading_time( $post_id = null ) {
    $content = get_post_field( 'post_content', $post_id ?: get_the_ID() );
    $words   = str_word_count( wp_strip_all_tags( $content ) );
    $minutes = max( 1, (int) ceil( $words / 200 ) ); // ~200 words per minute
    return sprintf( '%d min read', $minutes );
}

add_filter( 'the_content', function ( $content ) {
    if ( is_singular( 'post' ) && in_the_loop() && is_main_query() ) {
        $label = '<p class="reading-time">' . esc_html( pc_reading_time() ) . '</p>';
        return $label . $content;
    }
    return $content;
} );

How it works: it strips HTML and shortcodes, counts words and divides by 200 — a common average for on-screen reading. The in_the_loop() and is_main_query() checks stop the label from appearing in sidebars, excerpts and related-post widgets.

Watch out: str_word_count() only counts Latin-alphabet words. For Urdu, Arabic or Hindi content, count with preg_split('/\s+/u', ...) instead. Full version: WordPress reading time for posts.

3. Log slow database queries in Laravel

"The dashboard is slow" is the most common complaint in any Laravel app — and the cause is almost always one query. This snippet writes every query slower than 500 ms to your log with its SQL, bindings and duration.

// app/Providers/AppServiceProvider.php
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

public function boot(): void
{
    DB::listen(function (QueryExecuted $query) {
        if ($query->time > 500) { // milliseconds
            Log::warning('Slow query', [
                'sql'        => $query->sql,
                'bindings'   => $query->bindings,
                'time_ms'    => $query->time,
                'connection' => $query->connectionName,
                'url'        => request()->fullUrl(),
            ]);
        }
    });
}

Laravel also has a built-in helper for the total time spent querying in one request, which catches N+1 problems where each query is fast but there are hundreds of them:

DB::whenQueryingForLongerThan(2000, function ($connection, $event) {
    Log::warning("Request spent over 2s in the database on {$connection->getName()}");
});

What to do with the log: run the logged SQL with EXPLAIN in MySQL. If you see type: ALL (a full table scan), add an index on the column in the WHERE or ORDER BY. If the same query appears 200 times per request, eager-load the relationship with with().

Watch out: bindings can contain personal data such as emails. Keep this log private, and do not ship logs to third-party services without masking them. Full version: Log slow database queries in Laravel.

4. Organize your Downloads folder with Python

Thirty seconds of Python turns a Downloads folder with 900 random files into neat sub-folders by type. It runs in dry-run mode first, so you see exactly what will move before anything moves.

from pathlib import Path
import shutil

CATEGORIES = {
    "Images":    {".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg"},
    "Documents": {".pdf", ".docx", ".doc", ".txt", ".xlsx", ".csv", ".pptx"},
    "Archives":  {".zip", ".rar", ".7z", ".tar", ".gz"},
    "Video":     {".mp4", ".mov", ".mkv", ".avi"},
    "Audio":     {".mp3", ".wav", ".m4a"},
    "Installers":{".exe", ".msi", ".dmg", ".apk"},
    "Code":      {".py", ".js", ".php", ".html", ".css", ".json", ".sql"},
}

def category_for(path: Path) -> str:
    ext = path.suffix.lower()
    for name, extensions in CATEGORIES.items():
        if ext in extensions:
            return name
    return "Other"

def organize(folder: Path, dry_run: bool = True) -> None:
    for item in folder.iterdir():
        if not item.is_file() or item.name.startswith("."):
            continue
        dest_dir = folder / category_for(item)
        target = dest_dir / item.name
        counter = 1
        while target.exists():  # never overwrite: report (1).pdf, report (2).pdf ...
            target = dest_dir / f"{item.stem} ({counter}){item.suffix}"
            counter += 1
        print(f"{'[dry-run] ' if dry_run else ''}{item.name} -> {dest_dir.name}/{target.name}")
        if not dry_run:
            dest_dir.mkdir(exist_ok=True)
            shutil.move(str(item), str(target))

if __name__ == "__main__":
    organize(Path.home() / "Downloads", dry_run=True)  # set False when happy

How it works: pathlib walks the folder, each file's extension decides its category, and a counter guarantees no file is ever overwritten. Uses only the standard library — nothing to install.

Make it automatic: schedule it daily with Task Scheduler on Windows or cron on macOS and Linux. Full version: Organize Downloads folder by file type.

5. Bulk resize images and convert them to WebP

Oversized images are the number-one cause of slow pages and poor Largest Contentful Paint (LCP) scores. This script resizes a whole folder to a maximum width and converts everything to WebP, usually cutting file size by 60–80%.

# pip install pillow
from pathlib import Path
from PIL import Image, ImageOps

SRC = Path("images")
OUT = Path("images-webp")
MAX_WIDTH = 1600
QUALITY = 80

OUT.mkdir(exist_ok=True)
for path in SRC.iterdir():
    if path.suffix.lower() not in {".jpg", ".jpeg", ".png"}:
        continue
    with Image.open(path) as im:
        im = ImageOps.exif_transpose(im)          # fix phone photos shown sideways
        if im.mode in ("P", "LA"):
            im = im.convert("RGBA")              # keep transparency for PNGs
        elif im.mode not in ("RGB", "RGBA"):
            im = im.convert("RGB")
        if im.width > MAX_WIDTH:
            ratio = MAX_WIDTH / im.width
            im = im.resize((MAX_WIDTH, round(im.height * ratio)), Image.LANCZOS)
        target = OUT / f"{path.stem}.webp"
        im.save(target, "WEBP", quality=QUALITY, method=6)
        print(f"{path.name}: {path.stat().st_size // 1024} KB -> {target.stat().st_size // 1024} KB")

Watch out: without exif_transpose(), many phone photos come out rotated. Keep the originals — WebP at quality 80 is lossy, and you may want to re-export later. Full version: Bulk image resizer and WebP converter.

How to use snippets safely

  • Test on staging first. A typo in functions.php or wp-config.php can take a WordPress site down.
  • Back up before anything that deletes — especially the revision cleanup command.
  • Use a child theme or a small custom plugin for WordPress code, so theme updates do not wipe your changes.
  • Read the code before you paste it. If you cannot explain what a line does, that is the line to look up. Our OWASP Top 10 guide shows the security mistakes to look for.

FAQ

Where should I put WordPress snippets — functions.php or a plugin?

For site-specific behaviour that should survive a theme change (like revision limits), a small custom plugin or a snippets plugin is safer. For display tweaks tied to your theme (like reading time placement), a child theme's functions.php is fine.

Does the Laravel slow query logger slow down my app?

The overhead is tiny — one comparison per query. It is safe to keep in production, as long as the log file is rotated (use the daily log channel).

Is WebP supported by all browsers?

Yes. All modern browsers, including Safari since version 14, support WebP. For very old browsers, serve a JPEG fallback with the <picture> element.

What to learn next

Snippets solve symptoms; understanding solves the next ten problems. If slow queries interest you, read System Design Basics. If you are deploying Laravel yourself, follow our Laravel VPS deployment guide. And browse all 30 snippets in the snippets library.

Found this useful? Share it

AD

Admin PenduCoder

Full-stack developer and educator. Writes about Laravel, Next.js, applied AI and the unglamorous parts of shipping software.

Get in touch →
Chat with us