Skip to content
Ruhani RabinRuhani Rabin
Snippets

Code Snippets

Copy-paste-ready code snippets for your next project.

How to Add Source Code Highlights in Bricks Builder + Core Framework

How to Add Source Code Highlights in Bricks Builder + Core Framework

Enhancing the readability and functionality of your source code snippets can be a game-changer for your WordPress site. Today, let's talk about how to add source code highlights and a handy "Copy Code" button to your site - specially for Bricksbuilder with Core framework— without using any plugins! Highlight.js Initialization First, we'll use Highlight.js to make your code snippets look great. Highlight.js is a fantastic library that automatically styles your code snippets, making them more readable and aesthetically pleasing. Step 1: Enqueue Highlight.js Scripts and Styles To start, we'll need to load the Highlight.js library and its CSS styles from a CDN. This ensures that your code snippets are styled correctly. Step 2: Adding Copy Code Button Next, we enhance the Highlight.js functionality by adding a " Copy Code " button to each code block. This button lets users easily copy code snippets to their clipboard with just one click! Making it Work Using a bit of PHP, we can enqueue the necessary scripts and styles, then add a JavaScript snippet that initializes Highlight.js and appends the "Copy Code" button to each code block. Step 3: Wrap Standalone Code Tags To ensure all your standalone <code> tags within <p> tags are correctly highlighted, a PHP filter will wrap these within <pre> tags. This is a crucial step for consistent styling. Step 4: Custom Styles Finally, we add custom CSS styles. This will style the pre and code elements and the " Copy Code " button, ensuring everything looks clean and professional. And that's it! You've now enhanced your WordPress site with beautifully highlighted code that's easy to copy. This improves the aesthetic and enhances user experience by making code snippets more functional and user-friendly.

WPCodeBox
Automatically Make WordPress Tables Blocks Responsive for Mobile

Automatically Make WordPress Tables Blocks Responsive for Mobile

WordPress block tables break on mobile. Headers disappear, content gets squished, and users scroll horizontally to read your data. Not ideal. Most plugins add bloat. You get features you don't need, extra database queries, and another thing to update. The Solution This code snippet makes your WordPress block tables responsive automatically. No plugin required. Here's what happens on mobile: Tables stack vertically instead of side-by-side Each row becomes its own section Column headers appear next to their data Colors adapt to your theme (light or dark mode) How It Works The snippet has two parts: CSS (Mobile Styles) Triggers at 650px screen width Converts table rows and cells to block display Hides the original header row Shows column labels inline with data Uses your theme's color variables for consistency JavaScript (Dynamic Labels) Reads your table headers automatically Adds labels to each cell using data-column-label attributes Runs on page load for all block tables Installation Option 1: functions.php Copy the code into your child theme's functions.php file. Option 2: Code Snippets Plugin Install “Fluent Snippets” or “WPCodeBox”, create a new snippet, paste the code, and activate. Compatibility Works with: WordPress block tables (Gutenberg) Bricks Builder Core Framework Any theme using CSS variables for colors The code uses Core Framework variables ( --color-background , --color-text ) with fallbacks for standard themes. What You Get Before (Mobile): Horizontal scrolling Hidden columns Cramped content After (Mobile): Clean vertical layout All data visible Column headers inline Theme-matched colors Code Features Inline comments explaining each section Non-breaking spaces in labels (proper rendering) No external dependencies Performance Zero impact on desktop. Mobile gets a small inline CSS block and lightweight JavaScript that runs once on page load. No external files, no HTTP requests. When to Use This You have tables in your content and need them mobile-friendly. You don't want a plugin. You're comfortable adding code to your site. When Not to Use This You already have a table plugin that handles responsive design. You need advanced features like sorting, filtering, or CSV imports. You want a no-code solution with a visual interface.

WPCodeBox
WordPress: Auto-Import External Images to Media Library (Block Editor Compatible)

WordPress: Auto-Import External Images to Media Library (Block Editor Compatible)

If you've ever pasted content from Google Docs, copied images from other websites, or imported posts that reference external image URLs, you know the pain: WordPress keeps those images as remote links. They're not in your media library. They break when the source site removes them. And WordPress doesn't even recognize them as “real” images. I built this plugin to solve exactly that problem. Every time you save a post, it automatically downloads all external images, uploads them to your media library, and updates your content to use the local versions. No manual intervention is needed. What This Plugin Does When you save any post or page (draft, published, or whatever), this plugin: Scans your content for any external image URLs Downloads each image to your server Creates a proper media library entry with all the metadata Replaces the entire image tag with WordPress-native markup Adds responsive image sizes (srcset, sizes attributes) Includes the wp-image-{ID} class so WordPress knows it's local It works with both the classic editor and the block editor (Gutenberg). It even handles Google Docs images and other redirected URLs. Key Features Smart Image Naming Images are named based on your post title, not random URLs. If your post is “ChatGPT vs Claude vs Gemini for Product Strategy,” the images become: chatgpt-vs-claude-vs-gemini-for-product-strategy.jpg chatgpt-vs-claude-vs-gemini-for-product-strategy-2.jpg chatgpt-vs-claude-vs-gemini-for-product-strategy-3.jpg Optional Metadata Auto-Fill You can configure whether the plugin auto-fills: Image title Alt text Caption Description By default, all are set to false so you control this yourself. Performance Safeguards Maximum 50 images per save (configurable) Content size limit of 5 MB to prevent timeouts Deduplication - won't re-download images that already exist Stores a map of processed URLs to avoid redundant downloads Block Editor Compatible This version (2.0.0) is a complete rewrite that properly integrates with Gutenberg. The images now include: Proper wp-image-{ID} classes Responsive image sizes (thumbnail, medium, large, full) Srcset and sizes attributes for responsive loading Integration with WordPress's native image handling Configuration At the top of the plugin file, you'll find these settings: php define ( 'RR_EXTIMG_SET_TITLE' , false ) ; define ( 'RR_EXTIMG_SET_ALT' , false ) ; define ( 'RR_EXTIMG_SET_CAPTION' , false ) ; define ( 'RR_EXTIMG_SET_DESCRIPTION' , false ) ; define ( 'RR_EXTIMG_DEFAULT_SIZE' , 'large' ) ; Set any to true to auto-fill that metadata field. The RR_EXTIMG_DEFAULT_SIZE controls which image size gets used in your content (options: thumbnail , medium , large , full ). How It Works (Technical Overview) The plugin hooks into WordPress's save process at multiple points: save_post hook - Catches manual saves in the admin rest_after_insert_post hook - Catches block editor saves via REST API rest_after_insert_page hook - Catches page saves via REST API When triggered, it: Extracts Images: Parses HTML for <img> tags Also parses Gutenberg block JSON for image URLs Captures the full tag, not just the src Validates & Downloads: Checks if URL is external (not your own domain) Validates image extension (jpg, png, gif, webp, svg, ico, bmp) Handles Google Docs/Drive redirects Downloads to temp file using WordPress's download_url() Creates Media Entry: Uses media_handle_sideload() for proper WordPress integration Generates all responsive image sizes Stores original URL as post meta for reference Optionally fills in title, alt, caption, and description Replaces Content: Generates proper WordPress image HTML with all attributes Includes wp-image-{ID} class Adds srcset and sizes for responsive images Replaces the entire <img> tag in your content Updates the post without triggering another save loop Stores Mapping: Monitors which URLs have been processed Prevents re-downloading on subsequent saves Stored as post meta: _rr_extimg_map Use Cases I use this for: Content imports from other sites or Google Docs Guest posts where contributors paste content with external images Legacy content migration to ensure all images are local SEO to control image file names and metadata Site reliability - no more broken images when external sites go down Installation Method 1: Manual Installation Copy the plugin code into a new file: wp-content/plugins/rr-import-external-images/rr-import-external-images.php Activate the plugin: Go to WordPress Admin → Plugins Find “RR — Import External Images on Save” Click Activate Method 2: Use a Code Snippet plugin like WPCodeBox or FluentSnippets. Copy the snippet below and paste it in your favorite code snippet plugin.

WPCodeBox
Auto Featured Image by Post Types Using Robolly API and Templates

Auto Featured Image by Post Types Using Robolly API and Templates

This snippet uses Robolly Templates and API to generate Featured Images for a Specific Post Type. It has WP Admin page inside Settings > AFI—Robolly. Conditions: Requires Robolly Template to be done Requires Robolly API key A post with a published status, only if there is NO featured image already attached Setup credentials in Settings > AFI — Robolly Operation: Set up a Template in Robolly Copy the Template ID and Robolly API Key Set up the preferences Now go to a published post or page Make sure there are no existing-featured images is set to the post Press Save — wait for it to work Refresh the post editor to see the new featured image [caption id="attachment_36162" align="alignnone" width="600"] Setup templates in Robolly[/caption] [caption id="attachment_36161" align="alignnone" width="320"] Once published, the featured image is created automatically using the Robolly API and Template[/caption] Works with: WP CodeBox FluentSnippets Other Code Snippets Plugins

WPCodeBox
WordPress Cron Job Cleanup Made Easy – My Cron Manager

WordPress Cron Job Cleanup Made Easy – My Cron Manager

Why Should You Care About WordPress Cron Jobs? Ever wondered why some parts of your WordPress website suddenly stop working, or why scheduled posts don't publish on time? The culprit might be hiding in your WordPress cron jobs. These behind-the-scenes tasks keep your website running smoothly, but when they go wrong, they can cause headaches. My Cron Manager My Cron Manager is a lightweight, user-friendly tool that gives you complete control over your WordPress cron jobs. Think of it as a task manager for your website - helping you see, manage, and clean up scheduled tasks that might be slowing down your site. What Can You Do With My Cron Manager? 1. View All Scheduled Tasks See exactly what's running on your site Check when tasks are scheduled to run Understand which plugins are creating scheduled jobs 2. Clean Up Your Site Remove orphaned cron jobs from deactivated plugins Delete unnecessary scheduled tasks Keep your WordPress database clean and efficient 3. Monitor System Health Check if WordPress cron is enabled View server time settings Track task schedules in real-time Key Benefits Complete Visibility : No more guessing what's running behind the scenes Better Performance : Remove unnecessary tasks that might slow down your site Easy Cleanup : One-click solution to remove orphaned cron jobs Time Management : See exactly when tasks are scheduled to run Safe Operations : Confirmation prompts prevent accidental deletions When Should You Use My Cron Manager? After uninstalling plugins When investigating site performance issues If scheduled posts aren't publishing correctly During website maintenance When troubleshooting automation issues Important Safety Tips Always Backup First : Before making any changes to cron jobs, backup your site Be Selective : Don't delete cron jobs unless you're sure what they do Test After Changes : Check your site's functionality after removing cron jobs Keep Records : Note which cron jobs you remove in case you need to restore them Who Should Use My Cron Manager? WordPress site administrators Web developers Site maintenance professionals Anyone managing multiple WordPress sites Installation and Usage Tips Install using your favorite code snippets plugin Access from Tools > My Cron Manager in WordPress admin Review existing cron jobs before making changes Use the "Clean Orphaned Crons" feature regularly for maintenance Common Questions Answered Q: Is it safe to delete cron jobs? A: Yes, if you know what they do. WordPress core cron jobs are protected from accidental deletion. Q: Will this slow down my site? A: No, My Cron Manager only runs in the admin area and has minimal impact on performance. Q: What happens if I delete a needed cron job? A: Most plugins will recreate their necessary cron jobs automatically when needed. Conclusion My Cron Manager is your Swiss Army knife for WordPress cron job management. It's simple enough for beginners but powerful enough for professionals. Regular maintenance of your cron jobs can improve site performance and prevent potential issues before they happen. Remember, while it's a powerful tool, always approach cron job management with caution and understanding. When in doubt, consult with a WordPress professional or keep the default settings.

WPCodeBox
Quick Access Menu – Custom Dropdown for WP Admin Bar with Options Page

Quick Access Menu – Custom Dropdown for WP Admin Bar with Options Page

This PHP code creates a WordPress plugin named "Custom Admin Bar Dropdown." The plugin adds a custom dropdown menu with configurable menu items to the WordPress admin bar. It includes a settings page where administrators can set the dropdown menu's title and define its items (title and URL). The settings page allows for the dynamic addition and removal of menu items through a user-friendly interface. Key Features: Custom Admin Bar Menu : Adds a customizable dropdown menu to the WordPress admin bar. Configuration Screen : This screen provides an interface in the WordPress admin area for configuring the dropdown menu's title and items. Dynamic Menu Management : Allows administrators to add and remove menu items dynamically through the settings page. Manage Menu Link : The dropdown menu automatically includes a "Manage Menu" link as the last item, linking to the settings page. User Permissions : Ensures only users with the 'manage_options' capability can access and modify the settings. This plugin is ideal for administrators who want to enhance the functionality of their WordPress admin bar with a custom, easily configurable dropdown menu.

WPCodeBox
How to Add Source Code Highlights and a Copy Button in WordPress

How to Add Source Code Highlights and a Copy Button in WordPress

Enhancing the readability and functionality of your source code snippets can be a game-changer for your WordPress site. Today, let's talk about how to add source code highlights and a handy "Copy Code" button to your site— without using any plugins! Highlight.js Initialization First, we'll use Highlight.js to make your code snippets look great. Highlight.js is a fantastic library that automatically styles your code snippets, making them more readable and aesthetically pleasing. Step 1: Enqueue Highlight.js Scripts and Styles To start, we'll need to load the Highlight.js library and its CSS styles from a CDN. This ensures that your code snippets are styled correctly. Step 2: Adding Copy Code Button Next, we enhance the Highlight.js functionality by adding a " Copy Code " button to each code block. This button lets users easily copy code snippets to their clipboard with just one click! Making it Work Using a bit of PHP, we can enqueue the necessary scripts and styles, then add a JavaScript snippet that initializes Highlight.js and appends the "Copy Code" button to each code block. Step 3: Wrap Standalone Code Tags To ensure all your standalone <code> tags within <p> tags are correctly highlighted, a PHP filter will wrap these within <pre> tags. This is a crucial step for consistent styling. Step 4: Custom Styles Finally, we add custom CSS styles. This will style the pre and code elements and the " Copy Code " button, ensuring everything looks clean and professional. And that's it! You've now enhanced your WordPress site with beautifully highlighted code that's easy to copy. This improves the aesthetic and enhances user experience by making code snippets more functional and user-friendly.

WPCodeBox
Shell/Bash Script Migrating WordPress – Find and Replace all Instance of Domain Name in WordPress or MySQL Database

Shell/Bash Script Migrating WordPress – Find and Replace all Instance of Domain Name in WordPress or MySQL Database

Migrating your WordPress site to a new domain or switching from HTTP to HTTPS can be daunting, especially when updating every instance of your old domain within your database. To simplify this process, we've created a powerful shell script that automates the entire procedure, ensuring a smooth and efficient transition. What This Script Does: Backup Your Database : Before making any changes, the script creates a comprehensive backup of your MySQL database. This ensures that you have a fallback option in case anything goes wrong. Compress the Backup : The script then compresses the SQL dump file into a .tar.gz Archive for easy storage and retrieval. Find and Replace Domain Instances : Utilizing the sed Command: the script searches for all instances of your old domain and replaces them with the new domain across the entire SQL dump file. Re-import the Database : Finally, the script re-imports the modified SQL file into your MySQL database, seamlessly updating all domain references.

Generic
Automatic Table of Content for Your WordPress Posts, Conditional Auto Insert before the First H2

Automatic Table of Content for Your WordPress Posts, Conditional Auto Insert before the First H2

Creating a Conditional Table of Contents for WordPress Posts. When enhancing the readability of long-form content, including a Table of Contents (TOC) is beneficial for your readers. On WordPress, you can automatically generate and insert a TOC for single post-entries that have structural headings (<h2> and <h3>) using the DOM Document class. However, to avoid clutter and maintain relevance, showing the TOC only when there are enough headings is prudent. Here, we'll demonstrate how to achieve this by showing the TOC only if there are more than two <h2> elements in your post content.

WPCodeBox
Automatically Assign ALT Text to Images in WordPress Posts If They are Missing

Automatically Assign ALT Text to Images in WordPress Posts If They are Missing

This PHP script is designed to automatically assign alt text to images in WordPress posts if they are missing it. The alt text is generated based on the post's title followed by an image counter. This ensures that all images have meaningful alt text, which is beneficial for SEO and accessibility. Function: auto_assign_alt_text_to_images Purpose The function auto_assign_alt_text_to_images processes the content of a WordPress post, identifies images without alt text, and assigns them alt text derived from the post's title. Parameters $content (string): The content of the WordPress post. Returns (string): The modified content with updated alt text for images. Logic Check if the post is a single post and has a featured image: if ( is_single () && has_post_thumbnail ( $post ->ID)) { Sanitize the post title: $post_title = sanitize_text_field ( $post ->post_title); Load the post content into a DOMDocument object: $doc = new DOMDocument (); @ $doc -> loadHTML ( mb_convert_encoding ( $content , 'HTML-ENTITIES' , 'UTF-8' )); Get all images in the post: $images = $doc -> getElementsByTagName ( 'img' ); Initialize an image counter: $image_counter = 1; Loop through each image and assign alt text if missing: foreach ( $images as $img ) { $alt = $img -> getAttribute ( 'alt' ); if ( empty ( $alt )) { $new_alt = $post_title . ' Image ' . $image_counter ; $img -> setAttribute ( 'alt' , $new_alt ); $image_counter ++; } } Save the modified content back to the $content variable: $content = $doc -> saveHTML (); Return the modified content: return $content ; Hook: add_filter The function auto_assign_alt_text_to_images is hooked into the the_content filter, ensuring it runs whenever the post content is processed. add_filter ( 'the_content' , 'auto_assign_alt_text_to_images' ); Example Before: < img src = "example.jpg" alt = "" > < img src = "example2.jpg" alt = "Already has alt text" > < img src = "example3.jpg" alt = "" > After: < img src = "example.jpg" alt = "Post Title Image 1" > < img src = "example2.jpg" alt = "Already has alt text" > < img src = "example3.jpg" alt = "Post Title Image 2" > In this example, the post title is "Post Title". The script adds "Post Title Image 1" and "Post Title Image 2" as alt text for the first and third images, respectively.

WPCodeBox