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

wpcanyon.com

BunnyCDN setup for WordPress (origin shield & query‑string cache)

Posted on August 19, 2025 By Admin No Comments on BunnyCDN setup for WordPress (origin shield & query‑string cache)

BunnyCDN Setup for WordPress (Origin Shield & Query-String Cache)

If you want to speed up your WordPress site globally and reduce server load, BunnyCDN is a reliable, cost-effective CDN solution. However, configuring BunnyCDN properly—especially with origin shield and query-string caching—can be tricky. This guide provides a quick fix and detailed steps to set up BunnyCDN with WordPress, ensuring optimal caching behavior and improved site performance.

Quick Fix: BunnyCDN WordPress Setup with Origin Shield & Query-String Cache

  1. Create a BunnyCDN Pull Zone pointing to your WordPress origin server.
  2. Enable Origin Shield in BunnyCDN dashboard to reduce origin hits.
  3. Configure BunnyCDN to cache query-string parameters correctly.
  4. Set appropriate cache-control headers in WordPress (via .htaccess or functions.php).
  5. Update your WordPress URLs to use the BunnyCDN Pull Zone URL.
  6. Test caching behavior and purge cache when necessary.

Why This Happens

WordPress sites often serve dynamic content with query strings (e.g., ?product_id=123), which many CDNs do not cache by default or cache incorrectly. Without proper query-string caching, users may get stale or incorrect content. Additionally, frequent origin requests can overload your server, especially during traffic spikes.

BunnyCDN’s Origin Shield acts as an additional caching layer between your origin and the CDN edge nodes, reducing origin load. Properly configuring query-string caching ensures that BunnyCDN caches unique versions of pages based on query parameters, improving cache hit ratio and user experience.

Requirements

  • Active BunnyCDN account
  • WordPress site with admin access
  • Access to your web server configuration (Apache, Nginx, or via cPanel/Plesk)
  • Basic knowledge of editing WordPress theme files or .htaccess

Step-by-step BunnyCDN WordPress Setup

1. Create a BunnyCDN Pull Zone

  1. Log in to your BunnyCDN dashboard.
  2. Go to Pull Zones and click Add Pull Zone.
  3. Enter a name (e.g., mywpsite), and set your WordPress site URL as the origin URL.
  4. Click Add Pull Zone and wait for the zone to be created.

2. Enable Origin Shield

  1. In your Pull Zone settings, navigate to the Origin Shield tab.
  2. Enable Origin Shield and select the closest region to your origin server.
  3. Save changes.

3. Configure Query-String Caching

  1. Go to the Cache tab in your Pull Zone settings.
  2. Under Query String Caching, select Cache every unique URL.
  3. Optionally, specify which query parameters to include or exclude.
  4. Save changes.

4. Set Cache-Control Headers in WordPress

To ensure BunnyCDN caches your content correctly, set proper cache-control headers. You can do this via .htaccess (Apache) or via WordPress functions.

Apache (.htaccess) example:

# BEGIN BunnyCDN Cache-Control
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType text/html "access plus 1 hour"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType text/css "access plus 1 week"
  ExpiresByType application/javascript "access plus 1 week"
</IfModule>

<IfModule mod_headers.c>
  Header set Cache-Control "public, max-age=3600"
</IfModule>
# END BunnyCDN Cache-Control

WordPress functions.php example:

function add_cache_control_headers() {
    if (is_admin()) return;
    header('Cache-Control: public, max-age=3600');
}
add_action('send_headers', 'add_cache_control_headers');

5. Replace URLs in WordPress to Use BunnyCDN

Update your WordPress URLs to serve static assets (images, CSS, JS) via BunnyCDN.

  • Use a plugin like Better Search Replace to replace URLs in your database from https://yourdomain.com/wp-content/ to https://yourpullzone.b-cdn.net/wp-content/.
  • Alternatively, use the WP Rocket or W3 Total Cache plugins to rewrite URLs for static files.

6. Test and Purge Cache

  1. Visit your site and inspect network requests to verify assets load from BunnyCDN URL.
  2. Use BunnyCDN’s cache control headers checker or browser dev tools to confirm caching.
  3. If you update content, purge BunnyCDN cache from the dashboard or via API.

Common Pitfalls

  • Not enabling query-string caching: Dynamic pages may serve stale or incorrect content.
  • Incorrect cache-control headers: BunnyCDN may not cache content or cache it too long.
  • Forgetting to update URLs: Static assets won’t load from BunnyCDN, missing performance benefits.
  • Origin Shield region mismatch: Selecting a distant region can increase latency.
  • Plugin conflicts: Some caching or security plugins may interfere with headers or CDN URLs.

Works on

Environment Notes
Apache Supports .htaccess cache headers and URL rewrites.
Nginx Requires manual config for cache-control headers; BunnyCDN works seamlessly.
LiteSpeed Compatible with .htaccess and cache headers.
cPanel / P
…
Speed & Security

WooCommerce: Disable shipping for virtual/downloadable products

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Disable shipping for virtual/downloadable products

WooCommerce: Disable Shipping for Virtual/Downloadable Products

If you run an online store using WooCommerce and sell virtual or downloadable products, you might want to disable shipping options for these products. Shipping is unnecessary for items that don’t require physical delivery, and disabling it improves the checkout experience and avoids confusion for customers. This tutorial shows you how to quickly disable shipping for virtual and downloadable products in WooCommerce with simple code snippets.

Quick Fix

  1. Add a custom function to your theme’s functions.php file or a site-specific plugin.
  2. Use WooCommerce hooks to conditionally remove shipping packages for virtual/downloadable products.
  3. Test your checkout to confirm shipping options do not appear for these products.

Why This Happens

By default, WooCommerce includes shipping calculations for all products unless they are explicitly marked as virtual or downloadable. Virtual products are intended to be intangible, such as services or memberships, while downloadable products are files customers can download after purchase. However, if a product is not properly configured or if shipping methods are not conditionally disabled, shipping options may still appear, causing confusion or unnecessary steps during checkout.

Requirements

  • WooCommerce installed and activated on your WordPress site.
  • Basic familiarity with editing theme files or creating a site-specific plugin.
  • Access to your WordPress admin dashboard or FTP/SFTP to add custom code.

Step-by-step: Disable Shipping for Virtual/Downloadable Products

  1. Backup your site. Before making any code changes, ensure you have a recent backup of your site files and database.
  2. Access your theme’s functions.php file. You can do this via WordPress admin under Appearance > Theme Editor or via FTP/SFTP.
  3. Add the following code snippet:
add_filter( 'woocommerce_cart_shipping_packages', 'disable_shipping_for_virtual_downloadable_products' );

function disable_shipping_for_virtual_downloadable_products( $packages ) {
    foreach ( $packages as $key => $package ) {
        $all_virtual = true;

        foreach ( $package['contents'] as $item ) {
            $product = $item['data'];

            if ( ! $product->is_virtual() && ! $product->is_downloadable() ) {
                $all_virtual = false;
                break;
            }
        }

        if ( $all_virtual ) {
            unset( $packages[ $key ] );
        }
    }

    return $packages;
}
  1. Save the file.
  2. Test your checkout. Add virtual or downloadable products to the cart and proceed to checkout. Shipping options should no longer appear. For physical products, shipping remains enabled.

Common Pitfalls

  • Not marking products as virtual or downloadable: The code depends on the product’s virtual or downloadable status. If these are not set correctly in the product edit screen, shipping will not be disabled.
  • Using caching plugins: Sometimes caching can prevent immediate reflection of changes. Clear your site and browser cache after adding code.
  • Theme or plugin conflicts: Some themes or shipping plugins may override WooCommerce shipping behavior. Test with default themes and disable conflicting plugins if needed.
  • Editing core WooCommerce files: Never edit WooCommerce core files directly; always use hooks and filters in your theme or custom plugin.

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Hosting panels: cPanel, Plesk, and others
  • WooCommerce versions 3.0 and above
  • Compatible with most themes and child themes that follow WooCommerce standards

FAQ

Q: Can I disable shipping only for downloadable products but not virtual ones?
A: Yes. Modify the condition inside the loop to check only $product->is_downloadable() instead of both virtual and downloadable.
Q: What if I want to disable shipping only on certain shipping methods?
A: You can customize the code further by filtering shipping methods or using WooCommerce’s woocommerce_package_rates filter to selectively hide methods.
Q: Does this affect shipping calculations or just the display of shipping options?
A: This removes shipping packages entirely for virtual/downloadable products, so shipping is neither calculated nor displayed for those products.
Q: Can I add this code via a plugin instead of the theme’s functions.php?
A: Absolutely. Creating a site-specific plugin is recommended to keep customizations separate from theme updates.
Q: Will this work if I have mixed carts with both physical and virtual/downloadable products?
A: Yes. Shipping will only be disabled for packages containing exclusively virtual/downloadable products. Physical products will still trigger shipping options.
…
WooCommerce How‑tos

Fix “Sorry, this file type is not permitted for security reasons”

Posted on August 19, 2025 By Admin No Comments on Fix “Sorry, this file type is not permitted for security reasons”

Fix “Sorry, this file type is not permitted for security reasons”

If you’ve ever tried uploading a file to WordPress and encountered the error message “Sorry, this file type is not permitted for security reasons”, you know how frustrating it can be. This error prevents you from uploading certain file types that WordPress does not allow by default. The quick fix is to enable support for those file types safely by adding a small snippet of code to your theme or a custom plugin.

Quick Fix

  1. Access your WordPress site files via FTP or your hosting file manager.
  2. Open your active theme’s functions.php file or create a site-specific plugin.
  3. Copy and paste the following code to allow additional file types (example allows SVG and JSON):
function custom_mime_types($mimes) {
    $mimes['svg'] = 'image/svg+xml';
    $mimes['json'] = 'application/json';
    return $mimes;
}
add_filter('upload_mimes', 'custom_mime_types');
  1. Save the file and try uploading your file again.

Why This Happens

WordPress restricts file uploads to a predefined list of MIME types for security reasons. This prevents potentially harmful files from being uploaded and executed on your server. When you try to upload a file type not on this list, WordPress blocks it and shows the error message.

Commonly blocked file types include SVG, JSON, and some custom file formats. While these files can be safe, WordPress errs on the side of caution. To allow these files, you need to explicitly add their MIME types to the allowed list.

Step-by-step: Fixing on Different Environments

1. Using functions.php (Works on all setups)

  1. Log in to your hosting control panel or use an FTP client.
  2. Navigate to /wp-content/themes/your-active-theme/.
  3. Open functions.php in a text editor.
  4. Add the following code at the end of the file:
function custom_mime_types($mimes) {
    $mimes['svg'] = 'image/svg+xml';
    $mimes['json'] = 'application/json';
    return $mimes;
}
add_filter('upload_mimes', 'custom_mime_types');
  1. Save and upload the file back to the server.
  2. Test uploading your file again.

2. Using a Site-Specific Plugin (Recommended for theme-independent fix)

  1. Create a new file named custom-mime-types.php on your local machine.
  2. Paste the following code inside:
<?php
/*
Plugin Name: Custom MIME Types
Description: Allow additional file types for upload.
Version: 1.0
Author: Your Name
*/

function custom_mime_types($mimes) {
    $mimes['svg'] = 'image/svg+xml';
    $mimes['json'] = 'application/json';
    return $mimes;
}
add_filter('upload_mimes', 'custom_mime_types');
  1. Save and upload this file to /wp-content/plugins/ via FTP or file manager.
  2. Go to WordPress admin > Plugins and activate Custom MIME Types.
  3. Try uploading your file again.

3. Nginx Configuration (Optional)

If you are using Nginx and still face issues after allowing MIME types in WordPress, you may need to add MIME types in your Nginx config:

http {
    ...
    types {
        image/svg+xml svg;
        application/json json;
        # other MIME types
    }
    ...
}

After editing, reload Nginx:

sudo nginx -s reload

4. Apache Configuration (Optional)

For Apache servers, ensure the MIME types are recognized by adding them to your .htaccess or Apache config:

AddType image/svg+xml svg
AddType application/json json

Restart Apache if you edited the main config:

sudo systemctl restart apache2

5. cPanel / Plesk Users

Both cPanel and Plesk allow you to edit MIME types via their control panels:

  • cPanel: Go to Advanced > MIME Types and add the new types.
  • Plesk: Navigate to Tools & Settings > MIME Types and add the required types.

After adding, retry your upload.

Works on

  • WordPress on Apache, Nginx, LiteSpeed servers
  • Hosting control panels: cPanel, Plesk, DirectAdmin
  • Any WordPress theme or custom plugin setup
  • Local development environments like LocalWP, XAMPP, MAMP

FAQ

Q: Is it safe to allow SVG uploads in WordPress?
A: SVG files can contain malicious code if not sanitized. Use a plugin like “Safe SVG” or sanitize SVG files before uploading.
Q: Can I allow all file types by disabling this check?
A: It’s not recommended as it poses a security risk. Always whitelist only the file types you need.
Q: Why do I still get the error after adding MIME types?
Check your server’s MIME type configuration (Nginx/Apache) and ensure caching or security plugins are not blocking uploads.
Q: Can I add MIME types via a plugin instead of code?
Yes. Plugins like “WP Add Mime Types” allow you to add MIME types via the admin interface without coding.
Q: Does this fix work for multisite WordPress installations?
Yes, but you may need to add the code in the main site’s functions.php or a network-activated plugin.
…
Fixes & Errors

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

Reduce TTFB on budget hosting (OPcache + object cache)

Posted on August 19, 2025 By Admin No Comments on Reduce TTFB on budget hosting (OPcache + object cache)

Reduce TTFB on Budget Hosting (OPcache + Object Cache)

Time To First Byte (TTFB) is a critical performance metric that measures how long it takes for a user’s browser to receive the first byte of data from your server. On budget WordPress hosting, TTFB can often be slow due to limited server resources. This tutorial shows you how to reduce TTFB effectively by enabling OPcache and an object cache, improving your site’s responsiveness without upgrading your hosting plan.

Quick Fix: Enable OPcache and Object Cache

  1. Verify your hosting supports PHP OPcache and enable it in your PHP configuration.
  2. Install and configure a persistent object cache like Redis or Memcached.
  3. Integrate the object cache with WordPress using a suitable plugin.
  4. Test your site’s TTFB before and after to confirm improvements.

Why This Happens

Budget hosting environments typically share resources among many users, leading to slower PHP execution and database queries. WordPress dynamically generates pages by running PHP scripts and querying the database on each request, which increases TTFB.

OPcache caches compiled PHP bytecode, so PHP scripts don’t need to be recompiled on every request, reducing CPU load and execution time.

Object caching stores database query results and other expensive computations in memory, allowing WordPress to serve data faster without repeated database hits.

Combining OPcache with a persistent object cache significantly reduces backend processing time, lowering TTFB even on limited hosting.

Requirements

  • Budget WordPress hosting with PHP 7.4 or higher (PHP 8.x preferred).
  • Access to PHP configuration (php.ini or hosting control panel).
  • Redis or Memcached service available on your server or via your hosting provider.
  • Ability to install WordPress plugins.

Step-by-step Guide

1. Enable OPcache in PHP

Check if OPcache is enabled by creating a phpinfo.php file in your WordPress root directory:

<?php
phpinfo();
?>

Access it via your browser (e.g., https://yourdomain.com/phpinfo.php) and look for the Zend OPcache section.

If OPcache is disabled, enable it by editing your php.ini file or using your hosting control panel’s PHP settings. Add or update these lines:

opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.validate_timestamps=1

Restart your web server or PHP-FPM process if you have control over it.

2. Install Redis or Memcached

Check if your hosting provider supports Redis or Memcached. If yes, enable the service via your control panel or request support.

If you have SSH access and permission, install Redis (example for Ubuntu):

sudo apt update
sudo apt install redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server

For Memcached:

sudo apt update
sudo apt install memcached
sudo systemctl enable memcached
sudo systemctl start memcached

3. Install and Configure Object Cache Plugin in WordPress

Use a plugin to connect WordPress with Redis or Memcached. Popular options:

  • Redis Object Cache (for Redis)
  • Memcached Redux (for Memcached)

Example: Installing Redis Object Cache

  1. Go to Plugins > Add New in your WordPress dashboard.
  2. Search for Redis Object Cache and install it.
  3. Activate the plugin.
  4. Go to Settings > Redis and click Enable Object Cache.

4. Verify Object Cache is Working

Use the plugin’s status page or install the Query Monitor plugin to check if object caching is active and reducing database queries.

5. Test TTFB Improvement

Use tools like GTmetrix, Pingdom, or WebPageTest to measure TTFB before and after enabling caching.

Common Pitfalls

  • OPcache not enabled: Some shared hosts disable OPcache by default. Confirm with your provider.
  • Redis/Memcached not available: Budget hosts may not support these services or restrict access.
  • Plugin conflicts: Object cache plugins can conflict with other caching or optimization plugins.
  • Incorrect configuration: Ensure Redis/Memcached connection details match your server setup.
  • Not clearing cache after changes: Always flush caches after plugin or theme updates.

Works on

Server Control Panel Cache Support
Apache, Nginx, LiteSpeed cPanel, Plesk, DirectAdmin PHP OPcache, Redis, Memcached

FAQ

Q: Can I enable OPcache on any shared hosting?
A: Not always. Many budget hosts enable OPcache by default, but some restrict access. Check with your hosting provider.
Q: Is Redis or Memcached better for object caching?
A: Both are effective. Redis offers more features and persistence, while Memcached is simpler. Use whichever your host supports.
Q: Will enabling these caches reduce my database size?
A: No, caching reduces query load and speeds up response times but does not affect database size.
Q: How often should I clear OPcache and object
…
Speed & Security

WooCommerce: Redirect after add to cart (to cart or checkout)

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Redirect after add to cart (to cart or checkout)

WooCommerce: Redirect after Add to Cart (to Cart or Checkout)

By default, WooCommerce keeps customers on the product page after they add an item to their cart. Sometimes, you want to improve the shopping experience by redirecting users immediately to the cart or checkout page after adding a product. This tutorial explains how to implement a redirect after add to cart in WooCommerce quickly and reliably.

Quick Fix: Redirect After Add to Cart

  1. Choose whether to redirect to the cart page or the checkout page.
  2. Add a snippet of PHP code to your theme’s functions.php file or a site-specific plugin.
  3. Test the add-to-cart button to confirm the redirect works as expected.

Why This Happens

WooCommerce’s default behavior is designed to keep customers browsing products after adding an item to their cart. This can be good for discovery but sometimes disrupts the flow for customers ready to purchase. Redirecting after add to cart streamlines the checkout process by taking users directly to the cart or checkout page, reducing friction and potentially increasing conversions.

Requirements

  • WooCommerce plugin installed and active.
  • Access to your WordPress theme’s functions.php file or a site-specific plugin to add custom code.
  • Basic knowledge of editing PHP files in WordPress.

Step-by-step: Redirect After Add to Cart

  1. Backup your site. Always back up your site before editing theme files.
  2. Access your theme’s functions.php file. You can do this via Appearance > Theme Editor in WordPress admin or via FTP.
  3. Add the redirect code snippet. Copy and paste one of the following snippets depending on where you want to redirect users.

Code Snippet: Redirect to Cart Page

add_filter( 'woocommerce_add_to_cart_redirect', 'custom_redirect_to_cart' );
function custom_redirect_to_cart() {
    return wc_get_cart_url();
}

Code Snippet: Redirect to Checkout Page

add_filter( 'woocommerce_add_to_cart_redirect', 'custom_redirect_to_checkout' );
function custom_redirect_to_checkout() {
    return wc_get_checkout_url();
}
  1. Save the file. After adding the code, save your changes.
  2. Test the functionality. Visit a product page, add a product to the cart, and verify you are redirected to the cart or checkout page as intended.

Common Pitfalls

  • Theme or plugin conflicts: Some themes or plugins may override WooCommerce’s add to cart behavior, preventing the redirect from working.
  • AJAX add to cart enabled: If your theme uses AJAX for add to cart, the redirect filter may not trigger because the page does not reload.
  • Editing the wrong file: Ensure you add the code to your active theme’s functions.php or a site-specific plugin, not a parent theme if using a child theme.
  • Cache issues: Browser or server caching can interfere with testing changes. Clear caches after updating code.

Works on

Server/Environment Compatibility
Apache Fully compatible
Nginx Fully compatible
LiteSpeed Fully compatible
cPanel Fully compatible
Plesk Fully compatible

FAQ

Q: Why doesn’t the redirect work on my site?
A: If your theme uses AJAX add to cart, the redirect filter won’t trigger because the page doesn’t reload. You may need to disable AJAX add to cart or use JavaScript-based redirects.
Q: Can I redirect to a custom page after add to cart?
A: Yes. Replace wc_get_cart_url() or wc_get_checkout_url() with the URL of your custom page in the redirect function.
Q: Is it safe to add this code to my theme’s functions.php file?
A: Yes, but changes will be lost if you update the theme. Use a child theme or a site-specific plugin to keep changes persistent.
Q: How do I disable the redirect and go back to default behavior?
A: Remove or comment out the redirect filter code from your functions.php file or plugin.
Q: Will this affect variable or grouped products?
A: The redirect applies globally to all products added to the cart. However, AJAX add to cart on variable or grouped products may behave differently depending on your theme.
…
WooCommerce How‑tos

Fix “Destination folder already exists” when installing plugins/themes

Posted on August 19, 2025 By Admin No Comments on Fix “Destination folder already exists” when installing plugins/themes

Fix “Destination folder already exists” when installing plugins/themes

If you’ve ever tried to install a plugin or theme in WordPress and encountered the error “Destination folder already exists”, you know it can be frustrating. This error prevents WordPress from unpacking and installing the new plugin or theme because a folder with the same name already exists on your server. The quick fix is to delete or rename the existing folder before retrying the installation.

Quick Fix

  1. Access your website’s files via FTP, SFTP, or your hosting control panel’s file manager.
  2. Navigate to wp-content/plugins for plugins or wp-content/themes for themes.
  3. Locate the folder named exactly as the plugin or theme you are trying to install.
  4. Delete or rename this folder (e.g., add -old to the folder name).
  5. Return to your WordPress dashboard and retry the plugin or theme installation.

Why this happens

WordPress installs plugins and themes by unpacking a ZIP archive into a folder inside wp-content/plugins or wp-content/themes. If a folder with the same name already exists, WordPress cannot overwrite it and throws the “Destination folder already exists” error.

This can happen if:

  • A previous installation or update failed and left files behind.
  • You manually uploaded the plugin or theme folder before.
  • A plugin or theme folder was not properly deleted.
  • File permissions or ownership issues prevent WordPress from removing the folder.

Step-by-step: Fix on Nginx/Apache with cPanel/Plesk

1. Access your server files

Use one of the following methods to access your WordPress files:

  • FTP/SFTP: Connect with an FTP client like FileZilla using your hosting credentials.
  • cPanel File Manager: Log in to cPanel, go to File Manager.
  • Plesk File Manager: Log in to Plesk, navigate to Files.

2. Navigate to the plugin or theme folder

cd public_html/wp-content/plugins
# or for themes
cd public_html/wp-content/themes

3. Identify the conflicting folder

Look for the folder with the same name as the plugin or theme you want to install. For example, if installing “my-plugin”, look for a folder named my-plugin.

4. Delete or rename the folder

To delete the folder via command line (if you have SSH access):

rm -rf my-plugin

If you use cPanel or Plesk File Manager, right-click the folder and select Delete or rename it to my-plugin-old.

5. Check file permissions (optional)

Ensure WordPress can write to the plugins/themes folder:

chmod 755 wp-content/plugins
chmod 755 wp-content/themes

If ownership is an issue, contact your hosting provider or set ownership to the web server user (e.g., www-data on Ubuntu):

chown -R www-data:www-data wp-content/plugins
chown -R www-data:www-data wp-content/themes

6. Retry plugin/theme installation

Go back to your WordPress dashboard and install the plugin or theme again. The error should no longer appear.

Works on

Server Control Panel Notes
Apache cPanel, Plesk Standard file permissions and ownership apply.
Nginx cPanel, Plesk Same fix applies; ensure correct user ownership.
LiteSpeed cPanel, Plesk Compatible with same file management steps.

FAQ

Q1: Can I just overwrite the existing folder instead of deleting it?
A1: WordPress does not overwrite existing folders during installation. You must delete or rename the folder first to avoid conflicts.
Q2: What if I don’t have FTP or file manager access?
A2: Contact your hosting provider’s support to assist with deleting or renaming the conflicting folder.
Q3: Could this error be caused by file permission issues?
A3: Yes. If WordPress cannot delete or overwrite folders due to permission problems, you may see this error. Fix permissions or ownership as shown above.
Q4: Is it safe to delete the existing plugin or theme folder?
A4: Only delete if you are sure the folder is from a failed or old installation. Back up your site if unsure.
Q5: How can I avoid this error in the future?
A5: Always delete plugins or themes from the WordPress dashboard instead of manually removing files. Ensure updates complete successfully.
…
Fixes & Errors

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

Best HTTP security headers for WordPress (with examples)

Posted on August 19, 2025 By Admin No Comments on Best HTTP security headers for WordPress (with examples)

Best HTTP Security Headers for WordPress (with Examples)

WordPress security headers are essential HTTP response headers that help protect your website from common web vulnerabilities. Adding the right security headers can prevent attacks like cross-site scripting (XSS), clickjacking, and data injection, improving your site’s overall security posture. This guide explains the best HTTP security headers for WordPress, why they matter, and how to implement them effectively.

Quick Fix: Add These Essential WordPress Security Headers

  1. Content-Security-Policy (CSP): Controls which resources the browser can load.
  2. Strict-Transport-Security (HSTS): Enforces HTTPS connections.
  3. X-Frame-Options: Prevents clickjacking by controlling iframe embedding.
  4. X-Content-Type-Options: Stops MIME type sniffing.
  5. Referrer-Policy: Controls how much referrer information is sent.
  6. Permissions-Policy: Restricts access to browser features.
  7. Expect-CT: Enforces Certificate Transparency to prevent misissued certificates.

Adding these headers to your WordPress site’s server configuration or via plugins will significantly improve your website’s security.

Why This Happens: The Need for WordPress Security Headers

By default, WordPress does not send many HTTP security headers. This leaves your site vulnerable to:

  • Cross-site scripting (XSS): Malicious scripts injected into your pages.
  • Clickjacking: Attackers embedding your site in iframes to trick users.
  • Man-in-the-middle attacks: Without HTTPS enforcement, data can be intercepted.
  • MIME sniffing: Browsers guessing content types, potentially executing malicious files.
  • Data leakage: Referrer headers exposing sensitive URLs.

Security headers instruct browsers on how to handle your site’s content safely, reducing these risks.

Step-by-Step: How to Implement WordPress Security Headers

Depending on your server environment, you can add security headers via your web server configuration or WordPress plugins. Below are examples for Apache, Nginx, and a PHP snippet for WordPress.

1. Apache (.htaccess) Configuration

# Content Security Policy
Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';"

# HTTP Strict Transport Security (HSTS)
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"

# X-Frame-Options to prevent clickjacking
Header set X-Frame-Options "SAMEORIGIN"

# Prevent MIME sniffing
Header set X-Content-Type-Options "nosniff"

# Referrer Policy
Header set Referrer-Policy "no-referrer-when-downgrade"

# Permissions Policy (formerly Feature-Policy)
Header set Permissions-Policy "geolocation=(), microphone=(), camera=()"

# Expect-CT for Certificate Transparency
Header set Expect-CT "max-age=86400, enforce"

2. Nginx Configuration

add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';" always;

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

add_header X-Frame-Options "SAMEORIGIN" always;

add_header X-Content-Type-Options "nosniff" always;

add_header Referrer-Policy "no-referrer-when-downgrade" always;

add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

add_header Expect-CT "max-age=86400, enforce" always;

3. WordPress PHP Snippet (functions.php or custom plugin)

function add_security_headers() {
    header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';");
    header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");
    header("X-Frame-Options: SAMEORIGIN");
    header("X-Content-Type-Options: nosniff");
    header("Referrer-Policy: no-referrer-when-downgrade");
    header("Permissions-Policy: geolocation=(), microphone=(), camera=()");
    header("Expect-CT: max-age=86400, enforce");
}
add_action('send_headers', 'add_security_headers');

Note: Adjust the Content-Security-Policy directives to match your site’s resources and trusted domains.

Verification: How to Check Your WordPress Security Headers

After implementing the headers, verify they are active using these methods:

  • Browser Developer Tools: Open your site, press F12, go to the Network tab, reload, and inspect the response headers.
  • Online Tools: Use services like securityheaders.com or Mozilla Observatory.
  • Command Line: Run curl -I https://yourdomain.com and look for the security headers in the output.

Works On

Environment Notes
Apache Modify .htaccess or server config files.
Nginx Edit server block configuration files.
LiteSpeed Compatible with Apache directives in .htaccess.
cPanel / Plesk Use built-in editors for Apache/Nginx configs or add PHP snippets.
WordPress Plugins Plugins like “HTTP Headers” or
…
Speed & Security

WooCommerce: Change “Add to cart” text per product type

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Change “Add to cart” text per product type

WooCommerce: Change “Add to cart” Text Per Product Type

If you want to customize the “Add to cart” button text in WooCommerce based on the product type, this guide will show you how to do it quickly and efficiently. Changing the button text per product type can improve user experience by providing context-specific calls to action, such as “Select options” for variable products or “Read more” for external products.

Quick Fix

  1. Identify the product types you want to customize (simple, variable, grouped, external).
  2. Add a custom function to your theme’s functions.php or a site-specific plugin.
  3. Use WooCommerce filters to change the button text based on product type.
  4. Test the changes on the frontend to confirm the new button text appears correctly.

Why This Happens

WooCommerce uses default button texts for different product types to guide customers appropriately. For example, variable products show “Select options” because customers need to choose variations before adding to cart. However, these defaults might not fit your store’s branding or messaging strategy. WooCommerce provides hooks and filters that allow developers to modify these texts without changing core files, ensuring updates won’t overwrite your customizations.

Requirements

  • WooCommerce installed and active on your WordPress site.
  • Access to your theme’s functions.php file or a custom plugin for adding PHP code.
  • Basic understanding of PHP and WordPress hooks.
  • Optional: Child theme to avoid losing changes on theme updates.

Step-by-step

  1. Backup your site: Always create a backup before editing theme files.
  2. Open your theme’s functions.php file: Use FTP, cPanel file manager, or the WordPress theme editor.
  3. Add the following code snippet:
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_text', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_text', 10, 2 );

function custom_add_to_cart_text( $text, $product ) {
    if ( ! is_a( $product, 'WC_Product' ) ) {
        return $text;
    }

    switch ( $product->get_type() ) {
        case 'simple':
            $text = __( 'Buy Now', 'your-text-domain' );
            break;
        case 'variable':
            $text = __( 'Choose Options', 'your-text-domain' );
            break;
        case 'grouped':
            $text = __( 'View Products', 'your-text-domain' );
            break;
        case 'external':
            $text = __( 'Visit Website', 'your-text-domain' );
            break;
        default:
            $text = __( 'Add to cart', 'your-text-domain' );
            break;
    }

    return $text;
}
  1. Save the file and refresh your WooCommerce shop and product pages. You should see the new button texts based on product types.

Common Pitfalls

  • Editing the wrong file: Always use a child theme or a custom plugin to avoid losing changes after updates.
  • Missing product type check: Ensure the product object is valid before calling methods to avoid PHP errors.
  • Not using translation functions: Use __() or _e() for strings to support localization.
  • Cache issues: Clear your site and browser cache if changes don’t appear immediately.
  • Conflicts with other plugins: Some plugins may override button texts; test with plugins disabled if needed.

Works on

This method works on any WooCommerce installation regardless of your web server or control panel:

  • Web servers: Apache, Nginx, LiteSpeed
  • Control panels: cPanel, Plesk, DirectAdmin
  • Hosting environments: Shared hosting, VPS, Dedicated servers
  • Compatible with most themes and WooCommerce versions (tested on WooCommerce 7.x and later)

FAQ

Q: Can I change the button text only on the shop/archive pages?
A: Yes. Use the woocommerce_product_add_to_cart_text filter for archive/shop pages and woocommerce_product_single_add_to_cart_text for single product pages. The example code above uses both.
Q: How do I translate the new button texts?
A: Wrap your strings with translation functions like __() and load your text domain properly in your theme or plugin. Use tools like Loco Translate to manage translations.
Q: What if I want different texts for specific products, not just product types?
A: You can extend the function to check product IDs or categories and return custom texts accordingly.
Q: Will this affect the functionality of the add to cart button?
No. This only changes the button text, not the underlying functionality.
Q: Can I use this code in a plugin instead of functions.php?
Yes. Creating a site-specific plugin is a best practice to keep your customizations independent of theme updates.
…
WooCommerce How‑tos

Posts pagination

Previous 1 … 3 4 5 … 10 Next

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