Skip to content
  • Quick Ref
  • Contact
  • About
wpcanyon.com

wpcanyon.com

Category: Admin & Blocks

Schedule database cleanup tasks with WP‑CLI

Posted on August 19, 2025 By Admin No Comments on Schedule database cleanup tasks with WP‑CLI

Schedule Database Cleanup Tasks with WP-CLI

Keeping your WordPress database clean is essential for optimal site performance and stability. Over time, databases accumulate overhead from post revisions, transients, spam comments, and other unnecessary data. Manually cleaning the database can be tedious, but with WP-CLI, you can automate and schedule these cleanup tasks efficiently.

This tutorial explains how to schedule WordPress database cleanup tasks using WP-CLI, ensuring your database stays optimized without manual intervention.

Quick Fix: Schedule WordPress Database Cleanup with WP-CLI

  1. Ensure WP-CLI is installed and accessible on your server.
  2. Create a shell script that runs WP-CLI database cleanup commands.
  3. Schedule the script to run automatically using cron jobs (Linux) or Task Scheduler (Windows).
  4. Verify the scheduled task runs correctly and cleans the database.

Why This Happens

WordPress databases accumulate unnecessary data such as:

  • Post revisions and auto-drafts
  • Expired transients
  • Spam and trashed comments
  • Orphaned metadata

This buildup slows down queries, increases backup sizes, and can cause site instability. While plugins offer cleanup options, they add overhead and require manual triggers. WP-CLI provides a lightweight, scriptable interface to run cleanup commands quickly and schedule them via cron, automating maintenance without extra plugins.

Requirements

  • SSH access to your WordPress server
  • WP-CLI installed and configured
  • Basic knowledge of cron jobs or task schedulers
  • WordPress site with database access

Step-by-Step: Schedule WordPress Database Cleanup with WP-CLI

1. Verify WP-CLI Installation

Connect to your server via SSH and run:

wp --info

This confirms WP-CLI is installed and working. If not installed, follow the official WP-CLI installation guide.

2. Test Database Cleanup Commands

WP-CLI offers commands to clean up your database. Test them manually first:

wp post delete $(wp post list --post_type='revision' --format=ids) --force
wp transient delete --expired
wp comment delete $(wp comment list --status=spam --format=ids) --force
wp comment delete $(wp comment list --status=trash --format=ids) --force

These commands delete post revisions, expired transients, spam comments, and trashed comments respectively.

3. Create a Shell Script for Cleanup

Create a file named wp-db-cleanup.sh in your home directory or a preferred location:

#!/bin/bash
# Navigate to WordPress root directory
cd /path/to/your/wordpress

# Delete post revisions
wp post delete $(wp post list --post_type='revision' --format=ids) --force

# Delete expired transients
wp transient delete --expired

# Delete spam comments
wp comment delete $(wp comment list --status=spam --format=ids) --force

# Delete trashed comments
wp comment delete $(wp comment list --status=trash --format=ids) --force

# Optimize database tables
wp db optimize

Replace /path/to/your/wordpress with the actual path to your WordPress installation.

Make the script executable:

chmod +x wp-db-cleanup.sh

4. Schedule the Script with Cron

Edit your crontab to schedule the cleanup script. For example, to run it weekly at 3 AM on Sundays:

crontab -e

Add the following line:

0 3 * * 0 /bin/bash /path/to/wp-db-cleanup.sh /path/to/wp-db-cleanup.log 2&1

This runs the script and logs output to wp-db-cleanup.log.

5. Verify Scheduled Task

Check the log file after the scheduled time to confirm the cleanup ran successfully:

cat /path/to/wp-db-cleanup.log

You can also manually run the script to test:

/bin/bash /path/to/wp-db-cleanup.sh

Common Pitfalls

  • Incorrect WordPress path: Ensure the script’s cd command points to the correct WordPress root directory.
  • Permission issues: The user running the cron job must have permission to execute WP-CLI and access the WordPress files.
  • Empty command arguments: If no revisions or spam comments exist, WP-CLI commands with empty ID lists may throw errors. You can add conditional checks in the script to avoid this.
  • WP-CLI environment: Cron jobs may run with a limited environment. Use absolute paths for WP-CLI if necessary (e.g., /usr/local/bin/wp).

Works On

Server Environment Notes
Linux (Ubuntu, CentOS, Debian) Supports cron jobs, WP-CLI installation straightforward
cPanel Hosting Use cPanel’s cron job interface; ensure WP-CLI path is correct
Plesk Hosting Supports scheduled tasks; configure WP-CLI path accordingly
LiteSpeed Servers Compatible with WP-CLI and cron jobs
Windows Servers Use Task Scheduler; WP-CLI requires PHP CLI and proper environment setup

FAQ

Q: Can I schedule database cleanup without WP-CLI?
A: Yes, plugins like WP-Optimize can automate cleanup, but WP-CLI is faster, lighter, and does not add plugin overhead.
Q: What if my site has a large number of revisions or comments?
A: WP-CLI handles large datasets efficiently. However, you
…
Admin & Blocks

Add custom dashboard widgets (useful shortcuts)

Posted on August 19, 2025 By Admin No Comments on Add custom dashboard widgets (useful shortcuts)

Add Custom Dashboard Widgets (Useful Shortcuts)

If you manage a WordPress site, adding custom dashboard widgets can greatly improve your workflow by providing quick access to important links, information, or tools right on your admin dashboard. This tutorial shows you how to create a custom dashboard widget in WordPress, making your admin area more functional and tailored to your needs.

Quick Fix: Add a Custom Dashboard Widget in WordPress

  1. Create a function to register your custom widget using wp_add_dashboard_widget().
  2. Hook this function into the wp_dashboard_setup action.
  3. Define the callback function that outputs the widget content (e.g., useful shortcuts).
  4. Place the code in your theme’s functions.php file or a custom plugin.

Why This Happens

By default, WordPress dashboard widgets display standard information like site health, quick drafts, or WordPress news. However, these widgets might not fit your specific workflow or provide the shortcuts you frequently need. WordPress provides a built-in API to add custom dashboard widgets, allowing you to personalize your admin area and improve efficiency.

Requirements

  • Access to your WordPress site’s functions.php file or ability to create a custom plugin.
  • Basic knowledge of PHP and WordPress hooks.
  • Administrator access to the WordPress dashboard.

Step-by-step: Add a Custom Dashboard Widget with Useful Shortcuts

  1. Create the widget registration function. This function will register your custom widget with WordPress.
  2. function my_custom_dashboard_widgets() {
        wp_add_dashboard_widget(
            'custom_shortcuts_widget',         // Widget slug.
            'Useful Shortcuts',                 // Widget title.
            'custom_shortcuts_widget_content'  // Display function.
        );
    }
    add_action('wp_dashboard_setup', 'my_custom_dashboard_widgets');
  3. Define the widget content callback. This function outputs the HTML content inside your widget.
  4. function custom_shortcuts_widget_content() {
        echo '<ul>';
        echo '<li><a href="' . admin_url('post-new.php') . '">Add New Post</a></li>';
        echo '<li><a href="' . admin_url('edit.php?post_type=page') . '">Manage Pages</a></li>';
        echo '<li><a href="' . admin_url('upload.php') . '">Media Library</a></li>';
        echo '<li><a href="' . admin_url('themes.php') . '">Themes</a></li>';
        echo '<li><a href="' . admin_url('plugins.php') . '">Plugins</a></li>';
        echo '<li><a href="' . admin_url('options-general.php') . '">Settings</a></li>';
        echo '</ul>';
    }
  5. Add the code to your site. You can add this code to your active theme’s functions.php file or create a simple plugin to keep it separate from your theme.

Common Pitfalls

  • Placing code in the wrong file: Adding the code to a plugin or functions.php file of a child theme is recommended to avoid losing changes during theme updates.
  • Syntax errors: Missing semicolons, brackets, or quotes can cause fatal errors. Always test on a staging site first.
  • Widget not showing: Ensure you have administrator privileges and the code is hooked correctly to wp_dashboard_setup.
  • Conflicts with other plugins: Rarely, other plugins may deregister dashboard widgets or interfere with hooks.

Works on

This method works on any standard WordPress installation regardless of the web server or control panel:

  • Web servers: Apache, Nginx, LiteSpeed
  • Control panels: cPanel, Plesk, DirectAdmin
  • WordPress versions: 4.0 and above (recommended to use latest version)

FAQ

Q: Can I add multiple custom dashboard widgets?
A: Yes, simply call wp_add_dashboard_widget() multiple times with different widget IDs and callback functions.
Q: How do I remove default dashboard widgets?
A: Use remove_meta_box() inside the wp_dashboard_setup hook to remove unwanted default widgets.
Q: Can I add widgets for specific user roles only?
A: Yes, check the current user’s role inside your registration function and conditionally add widgets.
Q: Is it possible to add dynamic content like recent posts or stats?
A: Absolutely. Your widget callback function can run any PHP code, including queries to display dynamic data.
Q: Will this affect front-end performance?
A: No, dashboard widgets only load in the WordPress admin area and do not impact the public-facing site.
…
Admin & Blocks

Change WordPress admin login URL (pros/cons & safe method)

Posted on August 19, 2025 By Admin No Comments on Change WordPress admin login URL (pros/cons & safe method)

Change WordPress Admin Login URL (Pros/Cons & Safe Method)

By default, WordPress admin login pages are accessed via /wp-login.php or /wp-admin/. This common URL is a frequent target for brute force attacks and automated bots. Changing your WordPress login URL can improve security by obscurity, but it must be done carefully to avoid locking yourself out or breaking your site.

This guide explains how to change WordPress login URL safely, the pros and cons of doing so, and provides step-by-step instructions to implement the change without causing issues.

Quick Fix: Change WordPress Login URL Safely

  1. Backup your WordPress site and database.
  2. Install a trusted plugin like WPS Hide Login or iThemes Security.
  3. Configure the plugin to set a custom login URL (e.g., /my-login).
  4. Save changes and test the new login URL in a private/incognito browser.
  5. Bookmark the new login URL and avoid using the default /wp-login.php.

Why Change the WordPress Login URL?

  • Reduce brute force attacks: Bots often target the default login URL to guess passwords.
  • Hide login page from casual attackers: Changing the URL adds a layer of obscurity.
  • Lower server load: Fewer login attempts on the default URL reduce resource usage.

However, changing the login URL is not a foolproof security solution. It should be combined with strong passwords, two-factor authentication, and other security best practices.

Pros and Cons of Changing the WordPress Login URL

Pros Cons
Reduces automated login attempts and brute force attacks. If misconfigured, you may lock yourself out of the admin area.
Improves security by obscurity. Some plugins or themes might rely on default login URLs and break.
Decreases server load caused by repeated login requests. Requires remembering or bookmarking the new login URL.

Step-by-Step: How to Change WordPress Login URL Safely

Follow these steps to safely change your WordPress login URL using a plugin. This method avoids editing core files or .htaccess rules, which can cause errors.

  1. Backup Your Site
    Before making any changes, backup your WordPress files and database using your hosting control panel or a plugin like UpdraftPlus.
  2. Install the WPS Hide Login Plugin
    Navigate to Plugins > Add New in your WordPress dashboard. Search for WPS Hide Login, install, and activate it.
  3. Configure the New Login URL
    Go to Settings > WPS Hide Login. Enter your desired login slug, for example my-login, in the Login URL field.
    my-login

    The logout and redirect URLs will update automatically.

  4. Save Changes
    Click Save Changes at the bottom of the page.
  5. Test the New Login URL
    Open a private or incognito browser window and visit https://yourdomain.com/my-login. Confirm you can access the login page.
  6. Do Not Use Default URLs
    Attempting to access /wp-login.php or /wp-admin/ will now redirect or show a 404 error, depending on plugin settings.

Verification: Confirm Your Login URL Change Works

  • Try logging in with the new URL from different browsers and devices.
  • Ensure you can log out and log back in without issues.
  • Check that no plugins or themes break due to the URL change.
  • Verify your security plugins or firewall rules do not block the new login URL.

If you encounter problems, disable the plugin via FTP or your hosting file manager by renaming its folder in /wp-content/plugins/ to regain access.

Works On

  • Web servers: Apache, Nginx, LiteSpeed
  • Hosting control panels: cPanel, Plesk, DirectAdmin
  • WordPress versions: 4.9 and above (tested with latest versions)
  • Compatible with most themes and plugins that do not hardcode login URLs

FAQ

Q: Can I change the login URL manually without a plugin?
A: It is possible but not recommended. Manual changes involve editing core files or .htaccess rules, which can cause errors and are overwritten during updates.
Q: Will changing the login URL improve my site’s security?
Changing the login URL adds a layer of obscurity and reduces automated attacks, but it should be combined with strong passwords, two-factor authentication, and security plugins.
Q: What if I forget the new login URL?
If you forget the custom login URL, you can disable the plugin via FTP by renaming its folder in /wp-content/plugins/. This restores the default login URLs.
Q: Does changing the login URL affect WooCommerce or other plugins?
Most plugins, including WooCommerce, do not rely on the login URL and will continue working normally. However, test your site after the change to ensure compatibility.
Q: Can I use security plugins to change the login URL?
Yes, many security plugins like iThemes Security and All In One WP Security offer login URL changing features with additional security options.
…
Admin & Blocks

Disable comments sitewide (and close on old posts)

Posted on August 19, 2025 By Admin No Comments on Disable comments sitewide (and close on old posts)

Disable Comments Sitewide (and Close on Old Posts) in WordPress

Comments can sometimes attract spam, require moderation, or simply no longer fit the purpose of your WordPress site. Disabling comments sitewide and closing comments on older posts is a straightforward way to maintain control over user interaction and reduce maintenance. This guide shows you how to quickly disable comments across your entire WordPress site and automatically close comments on posts older than a specified number of days.

Quick Fix: Disable Comments Sitewide

  1. Go to your WordPress admin dashboard.
  2. Navigate to Settings > Discussion.
  3. Uncheck Allow people to submit comments on new posts.
  4. Save changes.
  5. To disable comments on existing posts, use the bulk edit feature or apply a code snippet (see below).
  6. To close comments on old posts automatically, add a custom function to your theme’s functions.php file or a site-specific plugin.

Why This Happens

By default, WordPress allows comments on new posts unless disabled manually. Existing posts retain their comment status unless changed individually or programmatically. Older posts may continue to accept comments indefinitely, which can lead to spam or outdated discussions. Disabling comments sitewide and closing them on older posts helps maintain site cleanliness and reduces moderation workload.

Step-by-Step: Disable Comments Sitewide and Close on Old Posts

1. Disable Comments on New Posts via Settings

This prevents comments on all future posts.

Dashboard > Settings > Discussion
- Uncheck "Allow people to submit comments on new posts"
- Save Changes

2. Disable Comments on Existing Posts in Bulk

Use WordPress bulk edit to disable comments on existing posts:

  1. Go to Posts > All Posts.
  2. Select all posts (increase posts per page if needed).
  3. Choose Edit from the Bulk Actions dropdown and click Apply.
  4. Set Comments to Do not allow.
  5. Click Update.

3. Programmatically Close Comments on Old Posts

Add the following code snippet to your theme’s functions.php file or a site-specific plugin. This will automatically close comments on posts older than 30 days (adjustable):

function close_comments_on_old_posts( $open, $post_id ) {
    $days = 30; // Number of days after which comments close
    $post = get_post( $post_id );
    if ( 'post' === $post-post_type ) {
        $post_age = ( time() - strtotime( $post-post_date ) ) / DAY_IN_SECONDS;
        if ( $post_age $days ) {
            return false; // Close comments
        }
    }
    return $open;
}
add_filter( 'comments_open', 'close_comments_on_old_posts', 10, 2 );

4. Disable Comments on Other Content Types

To disable comments on pages or custom post types, extend the bulk edit or use this snippet to disable comments sitewide:

function disable_comments_everywhere() {
    // Disable support for comments and trackbacks in post types
    foreach ( get_post_types() as $post_type ) {
        if ( post_type_supports( $post_type, 'comments' ) ) {
            remove_post_type_support( $post_type, 'comments' );
            remove_post_type_support( $post_type, 'trackbacks' );
        }
    }
}
add_action( 'admin_init', 'disable_comments_everywhere' );

// Close comments on front-end
function filter_comments_open( $open, $post_id ) {
    return false;
}
add_filter( 'comments_open', 'filter_comments_open', 20, 2 );
add_filter( 'pings_open', 'filter_comments_open', 20, 2 );

Common Pitfalls

  • Theme or plugin overrides: Some themes or plugins may override comment settings. Check for theme options or plugin settings that enable comments independently.
  • Cached pages: If you use caching plugins or server caching, changes may not appear immediately. Clear caches after applying changes.
  • Bulk edit limits: Bulk editing posts is limited by the number of posts shown per page. Increase the number of posts per page or repeat the process for all pages.
  • Child theme usage: When adding code snippets, use a child theme or a site-specific plugin to avoid losing changes after theme updates.

Works on

This method works on all standard WordPress setups regardless of the web server:

  • Apache
  • Nginx
  • LiteSpeed
  • cPanel and Plesk hosting environments
  • Multisite WordPress installations (note: bulk edit applies per site)

FAQ

Q: Will disabling comments delete existing comments?
No, disabling comments only prevents new comments. Existing comments remain visible unless you delete them manually.
Q: Can I disable comments only on pages and not posts?
Yes. You can selectively disable comments by modifying the code snippet to target only the ‘page’ post type or use bulk edit on pages only.
Q: How do I re-enable comments later?
Simply reverse the changes: enable comments in Settings > Discussion, remove or comment out the code snippets, and bulk edit posts/pages to allow comments again.
Q: Does this method affect pingbacks and trackbacks?
The provided code disables both comments and pingbacks/trackbacks. You can adjust the filters if you want to keep pingbacks enabled.
Q: Is there a plugin alternative?
Yes, plugins like “Disable Comments” offer UI-based options to disable comments sitewide or selectively. However, manual code snippets provide more control and avoid plugin bloat.
…
Admin & Blocks

Redirect author archives to homepage (or page)

Posted on August 19, 2025 By Admin No Comments on Redirect author archives to homepage (or page)

Redirect Author Archives to Homepage (or Page) in WordPress

If you want to redirect author archive WordPress pages to your homepage or a custom page, this tutorial shows you how to do it quickly and effectively. Author archives often reveal usernames or create duplicate content issues, so redirecting them can improve security and SEO.

Quick Fix

  1. Add a simple PHP snippet to your theme’s functions.php file or a site-specific plugin.
  2. Choose whether to redirect to the homepage or a custom URL.
  3. Test the author archive URLs to confirm the redirect works.

Why This Happens

By default, WordPress generates author archive pages at URLs like yoursite.com/author/username. These pages list all posts by that author. However, if you only have one author or want to hide author information for security or SEO reasons, redirecting these archives is a common approach.

Redirecting author archives prevents:

  • Exposure of usernames that can be exploited in brute force attacks.
  • Duplicate content issues that may harm SEO rankings.
  • Unnecessary archive pages that don’t add value to your site.

Requirements

  • Access to your WordPress theme files or ability to add custom code via a plugin.
  • Basic knowledge of editing PHP files safely.
  • Optional: FTP or hosting control panel access for file editing.

Step-by-step Guide to Redirect Author Archives

  1. Backup your site. Always create a backup before editing theme files.
  2. Access your theme’s functions.php file. You can do this via WordPress Admin Dashboard under Appearance > Theme Editor, or via FTP/cPanel file manager.
  3. Add the redirect code snippet. Copy and paste the following code at the end of the functions.php file:
function redirect_author_archives() {
    if (is_author()) {
        wp_redirect(home_url(), 301);
        exit;
    }
}
add_action('template_redirect', 'redirect_author_archives');

This code checks if the current page is an author archive and redirects visitors to the homepage with a permanent (301) redirect.

  1. Redirect to a custom page (optional). If you want to redirect to a specific page instead of the homepage, replace home_url() with the URL of your choice, for example:
wp_redirect(home_url('/custom-page/'), 301);
  1. Save the changes. Update the file and clear any caching plugins or server caches.
  2. Test the redirect. Visit any author archive URL like yoursite.com/author/username to confirm it redirects correctly.

Common Pitfalls

  • Editing the wrong functions.php file: Make sure you edit the active theme’s file or use a child theme to avoid losing changes on updates.
  • Cache interference: Clear browser, plugin, and server caches after adding the code to see the redirect immediately.
  • Plugin conflicts: Some SEO or redirection plugins may override this behavior. Disable them temporarily to test.
  • Incorrect URL in redirect: Ensure the URL passed to wp_redirect() is correct and includes trailing slashes if needed.

Works on

Server/Environment Compatibility
Apache Fully compatible
Nginx Fully compatible
LiteSpeed Fully compatible
cPanel / Plesk Fully compatible
Any WordPress environment Compatible as long as PHP code can be added

FAQ

  1. Can I redirect author archives without editing functions.php?

    Yes, you can use a plugin like “Redirection” or an SEO plugin with redirect features, but adding code is lightweight and efficient.

  2. Will this affect SEO negatively?

    No, a 301 redirect tells search engines the author archive pages are permanently moved, preventing duplicate content issues.

  3. How do I redirect only specific authors?

    Modify the code to check for specific author IDs or usernames before redirecting. Example:

    function redirect_specific_author_archives() {
        if (is_author('username')) {
            wp_redirect(home_url(), 301);
            exit;
        }
    }
    add_action('template_redirect', 'redirect_specific_author_archives');
    
  4. What if I want to disable author archives instead of redirecting?

    You can disable author archives by returning a 404 status or using SEO plugins to noindex those pages.

  5. Is this method safe for multisite WordPress?

    Yes, but ensure you add the code to each site’s theme or a network-activated plugin if you want it site-wide.

…
Admin & Blocks

Add a custom user role with specific capabilities

Posted on August 19, 2025 By Admin No Comments on Add a custom user role with specific capabilities

Add a Custom User Role with Specific Capabilities in WordPress

When managing a WordPress site, you might need to create a custom user role tailored to your specific needs. This allows you to control exactly what users assigned to this role can and cannot do. The quick fix is to add a custom user role programmatically using WordPress functions, specifying the capabilities you want to grant.

Quick Fix: Add a Custom User Role in WordPress

  1. Open your theme’s functions.php file or create a custom plugin.
  2. Use the add_role() function to define the new role and its capabilities.
  3. Save the changes and assign the new role to users via the WordPress admin panel.

Why This Happens

WordPress comes with predefined user roles like Administrator, Editor, Author, Contributor, and Subscriber. However, these roles might not fit every use case. For example, you may want a role that can moderate comments but cannot publish posts, or a role that can manage WooCommerce orders but not access other admin areas. Adding a custom user role with specific capabilities lets you tailor user permissions precisely, improving security and workflow.

Requirements

  • Access to your WordPress site’s files (via FTP, cPanel, or hosting file manager).
  • Basic knowledge of PHP and WordPress theme/plugin editing.
  • Administrator access to the WordPress admin dashboard.

Step-by-Step: How to Add a Custom User Role with Specific Capabilities

  1. Backup your site — Always back up your site files and database before making code changes.
  2. Choose where to add the code — You can add the code to your theme’s functions.php file or create a simple custom plugin.
  3. Write the code to add the role — Use the add_role() function to create the new role and assign capabilities.
  4. Save and upload the file — If editing locally, upload the modified file to your server.
  5. Assign the new role to users — Go to WordPress admin Users Edit user Role dropdown to assign the custom role.

Code Snippet: Adding a Custom User Role

<?php
function add_custom_user_role() {
    add_role(
        'custom_moderator', // Role slug
        'Custom Moderator', // Display name
        array(
            'read' =true, // Can read content
            'edit_posts' =false, // Cannot edit posts
            'delete_posts' =false, // Cannot delete posts
            'moderate_comments' =true, // Can moderate comments
            'upload_files' =true, // Can upload files
            'manage_categories' =false, // Cannot manage categories
        )
    );
}
add_action('init', 'add_custom_user_role');
?>

This example creates a role called “Custom Moderator” that can read content, moderate comments, and upload files but cannot edit or delete posts.

Removing a Custom Role

If you want to remove the custom role later, use the remove_role() function:

<?php
function remove_custom_user_role() {
    remove_role('custom_moderator');
}
add_action('init', 'remove_custom_user_role');
?>

Note: Removing a role does not delete users assigned to it. You should reassign those users to another role before removing.

Common Pitfalls When Adding Custom User Roles

  • Adding roles on every page load: Calling add_role() on every page load can cause issues. It’s best to run it once or check if the role exists before adding.
  • Incorrect capability names: Using invalid or misspelled capabilities will result in unexpected behavior. Refer to the WordPress Roles and Capabilities documentation for valid capability names.
  • Not assigning the role to users: After adding a role, you must assign it to users manually or programmatically.
  • Forgetting to remove roles on plugin deactivation: If you add roles via a plugin, consider cleaning up by removing roles on plugin deactivation.
  • Role conflicts: Avoid using role slugs that conflict with existing roles or plugins.

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Hosting panels: cPanel, Plesk, DirectAdmin
  • WordPress versions: 4.0 and above (recommended to use latest stable version)
  • Compatible with both single and multisite WordPress installations

FAQ

Q1: Can I add multiple custom roles at once?
A: Yes, you can call add_role() multiple times with different slugs and capabilities within the same function or hook.
Q2: How do I check if a role already exists before adding it?
A: Use get_role('role_slug'). It returns null if the role does not exist. Example:
if (null === get_role('custom_moderator')) {
    add_role(...);
}
Q3: Can I modify capabilities of an existing role?
A: Yes, use get_role('role_slug') to get the role object, then add or remove capabilities with add_cap() and remove_cap().
Q4: Will custom roles be removed if I switch themes?
A: If you add roles in your theme’s functions.php, switching themes will remove those roles. To keep roles persistent, use a custom plugin.
Q5: How do I assign a custom role to a user programmatically?
A: Use the wp_update_user() function. Example:
wp_update_user(array(
    'ID' =$user_id,
    'role' ='custom_moderator'
));
…
Admin & Blocks

Allow SVG uploads safely (sanitize + preview)

Posted on August 19, 2025 By Admin No Comments on Allow SVG uploads safely (sanitize + preview)

Allow SVG Uploads Safely (Sanitize + Preview) in WordPress

By default, WordPress does not allow SVG file uploads due to security risks. However, SVGs are widely used for scalable, high-quality graphics. The challenge is to enable SVG uploads safely by sanitizing the files and allowing previews in the media library. This tutorial shows you how to allow SVG upload in WordPress securely with code snippets for sanitization and preview support.

Quick Fix: Enable Safe SVG Uploads in WordPress

  1. Add code to allow SVG MIME type in uploads.
  2. Sanitize uploaded SVG files to remove malicious code.
  3. Enable SVG previews in the WordPress media library.
  4. Test uploading and previewing SVG files.

Why This Happens

WordPress blocks SVG uploads by default because SVG files are XML-based and can contain malicious scripts or harmful code. Without sanitization, uploading SVGs can open security vulnerabilities such as cross-site scripting (XSS). Simply enabling SVG uploads without cleaning the files is risky.

To safely allow SVG uploads, you must:

  • Whitelist the SVG MIME type.
  • Sanitize the SVG content to strip out any harmful code.
  • Enable WordPress to generate previews for SVG files.

Step-by-Step: Allow and Sanitize SVG Uploads in WordPress

1. Allow SVG MIME Type

Add this code to your theme’s functions.php file or a custom plugin to permit SVG uploads:

function allow_svg_upload_mime_type( $mimes ) {
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}
add_filter( 'upload_mimes', 'allow_svg_upload_mime_type' );

2. Sanitize Uploaded SVG Files

Use the SVG Sanitizer PHP library to clean SVG files on upload. First, install it via Composer or manually include it in your plugin.

Example code to sanitize SVG uploads:

use enshrinedsvgSanitizeSanitizer;

function sanitize_svg_on_upload( $file ) {
    if ( $file['type'] === 'image/svg+xml' ) {
        $sanitizer = new Sanitizer();

        $dirtySVG = file_get_contents( $file['tmp_name'] );
        $cleanSVG = $sanitizer-sanitize( $dirtySVG );

        if ( $cleanSVG === false ) {
            $file['error'] = 'Invalid SVG file.';
            return $file;
        }

        file_put_contents( $file['tmp_name'], $cleanSVG );
    }
    return $file;
}
add_filter( 'wp_handle_upload_prefilter', 'sanitize_svg_on_upload' );

3. Enable SVG Previews in Media Library

WordPress does not generate thumbnails for SVGs by default. Add this code to display SVG previews:

function svg_media_preview( $response, $attachment, $meta ) {
    if ( $response['mime'] === 'image/svg+xml' ) {
        $response['icon'] = $response['url'];
        $response['thumb'] = $response['url'];
        $response['sizes'] = [
            'thumbnail' =[
                'url' =$response['url'],
                'width' =80,
                'height' =80,
                'mime-type' ='image/svg+xml',
            ],
            'medium' =[
                'url' =$response['url'],
                'width' =160,
                'height' =160,
                'mime-type' ='image/svg+xml',
            ],
        ];
    }
    return $response;
}
add_filter( 'wp_prepare_attachment_for_js', 'svg_media_preview', 10, 3 );

4. Test Your Setup

  1. Go to Media > Add New in your WordPress admin.
  2. Upload a sanitized SVG file.
  3. Verify the upload succeeds without errors.
  4. Check the media library to see the SVG preview thumbnail.

Common Pitfalls

  • Not sanitizing SVGs: Uploading raw SVGs can expose your site to XSS attacks.
  • Missing MIME type: Forgetting to add SVG MIME type causes upload errors.
  • Composer dependency: The SVG Sanitizer library requires Composer or manual inclusion.
  • Preview issues: Some themes/plugins may override media previews, causing SVG thumbnails not to show.
  • Caching: Browser or plugin caching might prevent updated SVG previews from appearing immediately.

Works on

This solution works on WordPress sites running on Apache, Nginx, or LiteSpeed web servers. It is compatible with hosting control panels like cPanel and Plesk. The PHP SVG Sanitizer library requires PHP 7.0 or higher.

FAQ

Q: Is it safe to allow SVG uploads in WordPress?
A: Yes, if you sanitize SVG files on upload to remove malicious code. Never allow raw SVG uploads without sanitization.
Q: Can I use a plugin instead of code?
A: Yes, plugins like “Safe SVG” handle sanitization and previews, but using code gives you more control and reduces plugin overhead.
Q: Why don’t SVG thumbnails show in the media library?
A: WordPress does not generate raster thumbnails for SVGs by default. The code snippet above forces SVG previews by using the SVG itself as a thumbnail.
Q: What if my SVG files are still blocked after adding the MIME type?
A: WordPress also checks file extensions and content. Make sure your SVG files have the correct extension and pass sanitization.
Q: Can I customize the SVG sanitization?
A: Yes, the SVG Sanitizer library allows configuring allowed tags and attributes. Refer to its documentation for advanced customization.
…
Admin & Blocks

Create and manage reusable blocks (patterns)

Posted on August 19, 2025 By Admin No Comments on Create and manage reusable blocks (patterns)

Create and Manage Reusable Blocks (Patterns) in WordPress

If you frequently use the same content layout or design elements in WordPress, creating reusable blocks (also known as block patterns) can save you time and maintain consistency. This tutorial explains how to create, manage, and use reusable blocks in WordPress quickly and efficiently.

Quick Fix: How to Create Reusable Blocks in WordPress

  1. Open the WordPress block editor (Gutenberg) on any post or page.
  2. Create or select the block(s) you want to reuse.
  3. Click the three-dot menu on the block toolbar and select Add to Reusable Blocks.
  4. Name your reusable block and save it.
  5. To insert the reusable block later, click the + Add Block button, go to the Reusable tab, and select your block.

Why This Happens

WordPress introduced reusable blocks to help users avoid repetitive work by saving blocks or groups of blocks as reusable components. This feature is especially useful for site-wide elements like call-to-action sections, disclaimers, or frequently used layouts. Without reusable blocks, you would have to recreate or copy-paste the same content repeatedly, which is inefficient and error-prone.

Requirements

  • WordPress 5.0 or higher (Gutenberg block editor included by default)
  • Access to the WordPress admin dashboard
  • Basic familiarity with the block editor interface

Step-by-Step: Create and Manage Reusable Blocks in WordPress

1. Create a Reusable Block

  1. Go to Posts > Add New or open an existing post/page.
  2. Add the block(s) you want to reuse. For example, a paragraph, image, or group block.
  3. Click on the block to select it. If you want to reuse multiple blocks, group them first by selecting all and clicking Group from the block toolbar.
  4. Click the three-dot menu icon (More options) on the block toolbar.
  5. Select Add to Reusable Blocks.
  6. Enter a descriptive name for your reusable block and click Save.

2. Insert a Reusable Block

  1. Open any post or page in the block editor.
  2. Click the + Add Block button.
  3. Switch to the Reusable tab.
  4. Select the reusable block you want to insert.

3. Manage Reusable Blocks

  1. In the WordPress admin sidebar, go to Manage All Reusable Blocks by clicking the Reusable tab in the block inserter and then Manage all at the bottom.
  2. Here you can edit, delete, or export reusable blocks.
  3. Editing a reusable block updates all instances of that block across your site.

Code Snippets: Registering Custom Block Patterns Programmatically

If you want to create reusable block patterns programmatically (for developers), add the following code to your theme’s functions.php or a custom plugin:

function mytheme_register_block_patterns() {
    if ( function_exists( 'register_block_pattern' ) ) {
        register_block_pattern(
            'mytheme/two-columns-text-image',
            array(
                'title'       =__( 'Two Columns: Text and Image', 'mytheme' ),
                'description' =_x( 'A two column layout with text on the left and image on the right.', 'Block pattern description', 'mytheme' ),
                'content'     ="
                    
                    

Insert your text here.

" ) ); } } add_action( 'init', 'mytheme_register_block_patterns' );

This registers a reusable block pattern that users can insert from the block inserter under the Patterns tab.

Common Pitfalls When Creating Reusable Blocks

  • Editing a reusable block changes all instances: When you edit a reusable block inside a post, it updates everywhere. To avoid this, convert the reusable block to regular blocks before editing by selecting it and clicking Convert to Regular Blocks.
  • Reusing dynamic content: Reusable blocks store static content. If you want dynamic content (e.g., latest posts), consider using block patterns with dynamic blocks or custom blocks.
  • Deleting reusable blocks: Deleting a reusable block from the management screen will remove it from all posts/pages where it is used.
  • Compatibility: Older WordPress versions (before 5.0) do not support reusable blocks.

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Hosting panels: cPanel, Plesk, and others
  • WordPress 5.0+ with Gutenberg block editor enabled
  • Compatible with most modern themes and plugins supporting the block editor

FAQ

Q1: Can I export reusable blocks and use them on another WordPress site?
A1: Yes. Go to Manage All Reusable Blocks, select the block, and use the export option to download a JSON file. Import it on another site via the block editor.
Q2: How do I update a reusable block without affecting existing posts?
A2: Convert the reusable block to regular blocks before editing. This breaks the link and edits only the current instance.
Q3: Can reusable blocks contain multiple blocks?
A3: Yes. You can group multiple blocks and save the group as a reusable block.
Q4: Are reusable blocks the same as
…
Admin & Blocks

Disable Gutenberg for specific post types

Posted on August 19, 2025 By Admin No Comments on Disable Gutenberg for specific post types

Disable Gutenberg for Specific Post Types

If you want to disable the Gutenberg block editor for certain post types in WordPress, this quick guide will show you how. By default, Gutenberg is enabled for all post types that support the editor, but sometimes you need to revert to the classic editor or a custom meta box interface for specific post types. The fix is simple: add a small code snippet to your theme or plugin to disable Gutenberg selectively.

Quick Fix

  1. Identify the post types where you want to disable Gutenberg.
  2. Add a PHP filter to disable Gutenberg for those post types.
  3. Place the code in your theme’s functions.php file or a custom plugin.
  4. Clear caches and test the post editor for the specified post types.

Why This Happens

Gutenberg is WordPress’s default block editor introduced in version 5.0. It automatically activates for all post types that declare support for the editor. However, some custom post types or legacy content require the classic editor or a different editing interface. WordPress does not provide a built-in UI to disable Gutenberg on a per-post-type basis, so developers must use filters to control its activation.

Requirements

  • WordPress 5.0 or higher with Gutenberg enabled.
  • Access to your theme’s functions.php file or ability to create a custom plugin.
  • Basic knowledge of PHP and WordPress hooks.

Step-by-step: Disable Gutenberg for Specific Post Types

  1. Open your theme’s functions.php file or create a custom plugin file.
  2. Insert the following PHP code snippet:
<?php
/**
 * Disable Gutenberg editor for specific post types.
 *
 * @param bool   $is_enabled Whether the editor is enabled.
 * @param string $post_type  The post type being checked.
 * @return bool
 */
function disable_gutenberg_for_post_types( $is_enabled, $post_type ) {
    // List post types to disable Gutenberg for
    $disabled_post_types = array( 'your_post_type', 'another_post_type' );

    if ( in_array( $post_type, $disabled_post_types, true ) ) {
        return false; // Disable Gutenberg
    }

    return $is_enabled; // Keep default behavior for others
}
add_filter( 'use_block_editor_for_post_type', 'disable_gutenberg_for_post_types', 10, 2 );
  1. Replace your_post_type and another_post_type with your actual post type slugs.
  2. Save the file and upload it to your server if editing locally.
  3. Clear any caching plugins or server caches.
  4. Test by editing a post of the specified post types; the classic editor or meta boxes should appear instead of Gutenberg.

Additional Tips

  • If you want to disable Gutenberg for all custom post types, you can modify the code to check if the post type is not ‘post’ or ‘page’.
  • To disable Gutenberg for all post types, return false unconditionally in the filter.

Common Pitfalls

  • Incorrect post type slug: Make sure you use the exact post type slug registered in WordPress.
  • Code placement: Adding the code in the wrong place (e.g., outside PHP tags) will cause errors.
  • Conflicts with plugins: Some plugins override editor settings; test with plugins disabled if issues arise.
  • Caching: Browser or server caching might show the old editor; clear caches after changes.
  • Editor support: This method only works if the post type supports the editor feature.

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Control panels: cPanel, Plesk, DirectAdmin
  • WordPress environments with PHP 7.0+ (recommended 7.4+)
  • Any WordPress theme or plugin setup where you can add PHP code

FAQ

Question Answer
Can I disable Gutenberg only for posts but keep it for pages? Yes. Use the code snippet and set $disabled_post_types = array('post'); to disable Gutenberg only for posts.
Will this code affect the REST API? No. This filter only controls the editor interface in the admin area. The REST API remains unaffected.
How do I find the post type slug? You can find it in the post type registration code or by inspecting the URL when editing a post (e.g., post.php?post=123&post_type=your_post_type).
Can I disable Gutenberg for all custom post types automatically? Yes. Modify the function to check if the post type is not ‘post’ or ‘page’ and return false accordingly.
Is there a plugin alternative to this code? Yes, plugins like “Classic Editor” or “Disable Gutenberg” offer UI options to disable Gutenberg per post type without coding.
…
Admin & Blocks

Duplicate a page or post without a plugin

Posted on August 19, 2025 By Admin No Comments on Duplicate a page or post without a plugin

Duplicate a Page or Post Without a Plugin in WordPress

Need to duplicate a page or post in WordPress but want to avoid installing another plugin? This quick guide shows you how to clone any page or post manually by adding a simple code snippet to your theme’s functions.php file. It’s a clean, lightweight solution that keeps your site fast and clutter-free.

Quick Fix: Duplicate a Page or Post Without a Plugin

  1. Access your WordPress theme’s functions.php file via FTP or the theme editor.
  2. Copy and paste the provided duplication function code into functions.php.
  3. Save the file and refresh your WordPress admin dashboard.
  4. Go to the Pages or Posts list, hover over the item you want to duplicate, and click the new “Duplicate” link.
  5. A draft copy of the page or post will be created immediately, ready for editing.

Why This Happens

WordPress does not include a built-in “duplicate” or “clone” feature for pages or posts. Many users rely on plugins to add this functionality, but plugins can add extra overhead and potential security risks. By adding a custom function, you can create a native duplication option that integrates seamlessly with your admin interface without relying on third-party code.

Requirements

  • Basic familiarity with editing WordPress theme files.
  • Access to your site’s functions.php file via FTP, SFTP, or the WordPress theme editor.
  • Administrator privileges in WordPress.
  • Backup your site before making any code changes to avoid accidental data loss.

Step-by-Step: Add Duplicate Page/Post Functionality

  1. Backup your site. Always create a full backup before editing theme files.
  2. Open your theme’s functions.php file. You can do this via FTP or from the WordPress dashboard under Appearance > Theme Editor.
  3. Paste the following code at the end of the functions.php file:
function rd_duplicate_post_as_draft(){
    global $wpdb;
    if (! (isset($_GET['post']) || isset($_POST['post']) || (isset($_REQUEST['action']) && 'rd_duplicate_post_as_draft' == $_REQUEST['action']))) {
        wp_die('No post to duplicate has been supplied!');
    }

    // Get the original post id
    $post_id = (isset($_GET['post']) ? absint($_GET['post']) : absint($_POST['post']));
    // Get the original post
    $post = get_post($post_id);

    // Check if post exists
    if (null == $post) {
        wp_die('Post does not exist!');
    }

    // Check user permissions
    if (!current_user_can('edit_posts')) {
        wp_die('You do not have sufficient permissions to duplicate this post.');
    }

    // New post data array
    $new_post = array(
        'post_title'     =$post-post_title . ' (Copy)',
        'post_content'   =$post-post_content,
        'post_status'    ='draft',
        'post_type'      =$post-post_type,
        'post_author'    =wp_get_current_user()-ID,
        'post_excerpt'   =$post-post_excerpt,
        'post_parent'    =$post-post_parent,
        'menu_order'     =$post-menu_order,
        'comment_status' =$post-comment_status,
        'ping_status'    =$post-ping_status,
        'post_password'  =$post-post_password,
        'to_ping'        =$post-to_ping,
        'pinged'         =$post-pinged,
        'post_content_filtered' =$post-post_content_filtered,
        'post_mime_type' =$post-post_mime_type,
        'guid'           ='',
    );

    // Insert the post by wp_insert_post()
    $new_post_id = wp_insert_post($new_post);

    // Copy taxonomies
    $taxonomies = get_object_taxonomies($post-post_type);
    foreach ($taxonomies as $taxonomy) {
        $post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' ='slugs'));
        wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);
    }

    // Copy post meta
    $post_meta = get_post_meta($post_id);
    foreach ($post_meta as $meta_key =$meta_values) {
        foreach ($meta_values as $meta_value) {
            add_post_meta($new_post_id, $meta_key, maybe_unserialize($meta_value));
        }
    }

    // Redirect to the edit post screen for the new draft
    wp_redirect(admin_url('post.php?action=edit&post=' . $new_post_id));
    exit;
}
add_action('admin_action_rd_duplicate_post_as_draft', 'rd_duplicate_post_as_draft');

function rd_duplicate_post_link($actions, $post) {
    if (current_user_can('edit_posts')) {
        $actions['duplicate'] = '';
    }
    return $actions;
}
add_filter('post_row_actions', 'rd_duplicate_post_link', 10, 2);
add_filter('page_row_actions', 'rd_duplicate_post_link', 10, 2);
  1. Save the functions.php file.
  2. Go to the Pages or Posts list in your WordPress admin. Hover over any item and click the new Duplicate link.
  3. Edit the duplicated draft. The copy will open in the editor as a draft, ready for your changes.

Common Pitfalls

  • Editing the wrong functions.php file: Make sure you edit the active theme’s functions.php. Child themes are recommended to avoid losing changes on updates.
  • Missing user permissions: The duplication function checks if the user can edit posts. If you don’t have sufficient rights, the link won’t appear or duplication will fail.
  • Meta data serialization: The code uses maybe_unserialize() to handle serialized meta values correctly. Avoid modifying this unless you understand serialization.
  • Taxonomies not copied: The code copies all taxonomies assigned to the original post, but custom taxonomies may require additional handling if they have complex relationships.

…
Admin & Blocks

Recent Posts

  • Top WordPress Themes for Blogs in 2025
  • WordPress Admin Panel Trick: Adding ID Field to the Posts Listing
  • Solution previous_posts_link and next_posts_link Not Working
  • Show Top Commentators in WordPress Without a Plugin
  • How to Style Admin Comments in WordPress

Recent Comments

    Archives

    • August 2025

    Categories

    • Admin & Blocks
    • Admin & UI
    • Automation
    • Automation & Plugins
    • Comments
    • Comparisons
    • Database & Revisions
    • Developer Snippets
    • Fixes & Errors
    • Media & Thumbnails
    • Queries & Pagination
    • Security
    • Speed & Security
    • Tips & Tricks
    • WooCommerce How‑tos
    • WordPress Snippets
    • WordPress Themes
    • Terms & Conditions
    • Affiliate Disclosure

    Copyright © 2025 wpcanyon.com.

    Powered by PressBook WordPress theme