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

wpcanyon.com

Automatically Create a Page on Theme Activation

Posted on August 20, 2025August 20, 2025 By Admin No Comments on Automatically Create a Page on Theme Activation

Automatically Create a Page on Theme Activation

When developing a WordPress theme, you might want to automatically create a specific page as soon as the theme is activated. This is useful for setting up default content like a homepage, contact page, or any custom landing page without requiring manual user intervention. This tutorial explains how to automatically create a page on theme activation with a quick fix, detailed steps, and code snippets.

Quick Fix

  1. Hook into the after_switch_theme action to trigger code on theme activation.
  2. Check if the page already exists to avoid duplicates.
  3. Create the page programmatically using wp_insert_post().
  4. Optionally, set the created page as the front page or assign a specific template.

Why This Happens

By default, WordPress does not create any pages when you activate a theme. Themes are primarily responsible for design and layout, while content is managed separately. However, some themes require default pages to function properly or to provide a better user experience out of the box. Automatically creating pages on theme activation streamlines setup and reduces user errors.

Step-by-Step

  1. Open your theme’s functions.php file. This is where you will add the activation hook and page creation code.
  2. Hook into after_switch_theme action. This hook runs once immediately after the theme is activated.
  3. Check if the page exists. Use get_page_by_title() to avoid creating duplicate pages on multiple activations.
  4. Create the page if it doesn’t exist. Use wp_insert_post() with the required parameters.
  5. Optionally set the page as the front page. Update WordPress options show_on_front and page_on_front to make the new page the homepage.

Code Snippets

<?php
// Hook into theme activation
add_action( 'after_switch_theme', 'mytheme_create_default_page' );

function mytheme_create_default_page() {
    $page_title = 'Welcome';
    $page_content = 'This is the default welcome page created automatically on theme activation.';
    $page_check = get_page_by_title( $page_title );

    // Only create the page if it doesn't exist
    if ( ! isset( $page_check-ID ) ) {
        $page_id = wp_insert_post( array(
            'post_title'    => wp_strip_all_tags( $page_title ),
            'post_content'  => $page_content,
            'post_status'   => 'publish',
            'post_author'   => 1,
            'post_type'     => 'page',
        ) );

        // Optional: Set this page as the front page
        if ( $page_id > 0 ) {
            update_option( 'show_on_front', 'page' );
            update_option( 'page_on_front', $page_id );
        }
    }
}
?>

Common Pitfalls

  • Duplicate pages: Not checking if the page already exists can lead to multiple identical pages on repeated theme activations.
  • Incorrect post author ID: Using a user ID that doesn’t exist will cause the page creation to fail. Usually, user ID 1 is the admin.
  • Not setting page status: Forgetting to set post_status to publish will create a draft page invisible to visitors.
  • Forgetting to update front page options: If you want the page as the homepage, you must update show_on_front and page_on_front.
  • Page templates: If your theme uses custom page templates, you can assign a template by setting the _wp_page_template post meta.

Test & Verify

  1. Activate your theme from the WordPress admin dashboard.
  2. Go to Pages > All Pages and confirm the new page appears.
  3. Visit the front end of your site to verify the page content and if it is set as the homepage.
  4. Deactivate and reactivate the theme to ensure no duplicate pages are created.
  5. Check for any PHP errors or warnings in your debug log.

Wrap-up

Automatically creating a page on theme activation improves user experience by providing default content immediately. By hooking into after_switch_theme and using wp_insert_post(), you can programmatically add pages safely and efficiently. Always check for existing pages to avoid duplicates and optionally set the new page as the front page for seamless integration.

Works on

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Control Panels cPanel, Plesk, DirectAdmin
WordPress Versions 4.7 and above (recommended latest)
PHP Versions 7.0 and above (recommended 7.4+)

FAQ

Q: Can I create multiple pages on theme activation?
A: Yes, simply repeat the page creation logic for each page, ensuring you check for existing pages to avoid duplicates.
Q: How do I assign a custom page template to the created page?
A: Use update_post_meta( $page_id, '_wp_page_template', 'template-file.php' ); after creating the page.
Q: What if the user deactivates and reactivates the theme?
A: The code checks for existing pages by title, so it won’t create duplicates on reactivation.
Q: Can I create posts instead of pages?
A: Yes, change post_type to post in wp_insert_post() to create posts.
Q: Is it possible to delete the created page on theme
…
Tips & Tricks

10 Effective Ways to Secure Your WordPress Blog

Posted on August 20, 2025August 20, 2025 By Admin No Comments on 10 Effective Ways to Secure Your WordPress Blog

10 Effective Ways to Secure Your WordPress Blog

WordPress is the most popular blogging platform, but its popularity also makes it a frequent target for hackers. Securing your WordPress blog is essential to protect your content, user data, and reputation. This guide provides 10 effective ways to secure your WordPress blog quickly and efficiently.

Quick Fix

  1. Keep WordPress core, themes, and plugins updated.
  2. Use strong, unique passwords and enable two-factor authentication.
  3. Install a reputable security plugin like Wordfence or Sucuri.
  4. Limit login attempts and change the default login URL.
  5. Disable file editing from the WordPress dashboard.
  6. Set correct file permissions on your server.
  7. Use SSL to encrypt data between your site and users.
  8. Backup your site regularly and store backups offsite.
  9. Disable directory listing on your server.
  10. Monitor your site for suspicious activity and malware.

Why This Happens

WordPress’s open-source nature and widespread use make it a prime target for automated attacks, brute force login attempts, and exploitation of outdated software vulnerabilities. Many issues arise from weak passwords, outdated plugins/themes, and misconfigured server settings. Without proper security measures, your blog is vulnerable to hacks, data theft, and defacement.

Step-by-Step: Securing Your WordPress Blog

1. Update WordPress Core, Themes, and Plugins

Always run the latest versions to patch known vulnerabilities.

Dashboard > Updates > Update Now

2. Use Strong Passwords and Enable Two-Factor Authentication (2FA)

Use a password manager to generate complex passwords and install a 2FA plugin such as Google Authenticator or Two Factor.

Plugins > Add New > Search "Two Factor" > Install & Activate

3. Install a Security Plugin

Security plugins provide firewall, malware scanning, and login protection.

Plugins > Add New > Search "Wordfence" or "Sucuri" > Install & Activate

4. Limit Login Attempts and Change Login URL

Prevent brute force attacks by limiting login attempts and hiding the default login page.

Plugins > Add New > Search "Limit Login Attempts Reloaded" > Install & Activate

To change login URL, use plugins like WPS Hide Login.

5. Disable File Editing in Dashboard

Prevent attackers from modifying theme or plugin files via the dashboard.

Add the following line to wp-config.php:
define('DISALLOW_FILE_EDIT', true);

6. Set Correct File Permissions

Restrict file access to prevent unauthorized changes.

SSH into your server and run:
find /path/to/wordpress/ -type d -exec chmod 755 {} ;
find /path/to/wordpress/ -type f -exec chmod 644 {} ;

7. Use SSL (HTTPS)

Encrypt data between your users and your site by enabling SSL.

Obtain a free SSL certificate with Let's Encrypt or use your hosting provider's SSL option.

8. Backup Your Site Regularly

Use plugins like UpdraftPlus or BackupBuddy to schedule backups and store them offsite.

Plugins > Add New > Search "UpdraftPlus" > Install & Activate

9. Disable Directory Listing

Prevent visitors from browsing your directories by adding this to your .htaccess file:

Options -Indexes

10. Monitor Your Site

Regularly scan your site for malware and suspicious activity using your security plugin or external services.

Code Snippets

Below are useful code snippets to add to your wp-config.php or .htaccess files for enhanced security.

Purpose Code File
Disable File Editing
define('DISALLOW_FILE_EDIT', true);
wp-config.php
Disable Directory Listing
Options -Indexes
.htaccess
Protect wp-config.php
<files wp-config.php>
order allow,deny
deny from all
</files>
.htaccess
Block Access to .htaccess
<files .htaccess>
order allow,deny
deny from all
</files>
.htaccess

Common Pitfalls

  • Ignoring updates — outdated software is the easiest target.
  • Using weak or reused passwords.
  • Installing plugins or themes from untrusted sources.
  • Not backing up before making major changes.
  • Leaving default settings like login URLs unchanged.

Test & Verify

  1. Use online tools like SSL Labs to verify SSL configuration.
  2. Test file permissions with SSH or FTP to ensure they are set correctly.
  3. Attempt login with incorrect passwords to verify login limits.
  4. Scan your site using security plugins or external malware scanners.
  5. Check backups by restoring on a staging environment.

Wrap-up

Securing your WordPress blog is a…

Security

REST API: authenticate with Application Passwords

Posted on August 19, 2025 By Admin No Comments on REST API: authenticate with Application Passwords

REST API: Authenticate with Application Passwords

When working with the WordPress REST API, authentication is essential to securely access or modify site data. One straightforward method is using Application Passwords, a built-in WordPress feature that allows external applications or scripts to authenticate without exposing your main user password. This tutorial explains how to authenticate REST API requests using Application Passwords, including practical code examples and testing tips.

When to Use Application Passwords for REST API Authentication

  • External integrations: When connecting third-party apps or services to your WordPress site.
  • Custom scripts: Automating tasks or data synchronization without manual login.
  • Limited access: Granting specific permissions without sharing your main password.
  • Security: Application Passwords can be revoked individually, improving control over API access.

Quick Fix: Authenticate REST API Requests with Application Passwords

  1. Create an Application Password for your user in WordPress admin.
  2. Use Basic Authentication with your username and Application Password in the REST API request header.
  3. Test the authentication with a simple GET request to a REST API endpoint.
  4. Optionally, add helper code to your functions.php or a mini-plugin to customize or extend authentication behavior.

Why This Happens

WordPress REST API requires authentication for endpoints that modify data or access sensitive information. Traditional methods like cookie authentication or OAuth can be complex or unsuitable for external apps. Application Passwords provide a simple, secure alternative by generating unique passwords tied to specific users, which can be used in HTTP Basic Auth headers. This method is supported natively since WordPress 5.6.

Step-by-step: Authenticate REST API with Application Passwords

1. Create an Application Password in WordPress

  1. Log in to your WordPress admin dashboard.
  2. Go to Users > Profile (or Users > Your Profile).
  3. Scroll down to the Application Passwords section.
  4. Enter a name for the new password (e.g., “API Access Script”) and click Add New Application Password.
  5. Copy the generated password immediately; you won’t see it again.

2. Use Basic Authentication with the REST API

Include the username and Application Password in the HTTP Authorization header using Basic Auth. The format is:

Authorization: Basic base64_encode( 'username:application_password' )

Example using curl (replace username and app_password accordingly):

curl --user username:app_password https://example.com/wp-json/wp/v2/posts

3. Add Optional Helper Code (functions.php or Mini-Plugin)

WordPress supports Application Passwords natively, but you can add custom validation or logging by hooking into authentication filters. Here’s a minimal example to log successful Application Password authentications:

<?php
add_filter( 'determine_current_user', function( $user_id ) {
    if ( defined( 'WP_APPLICATION_PASSWORDS_TESTING' ) && WP_APPLICATION_PASSWORDS_TESTING ) {
        error_log( 'User ID ' . $user_id . ' authenticated via Application Password.' );
    }
    return $user_id;
}, 20 );
?>

Add this code to your theme’s functions.php or create a mini-plugin by placing it in a PHP file inside wp-content/plugins/ and activating it.

4. Test the Authentication

Use a REST client like Postman, Insomnia, or curl to test your authentication:

  • Set the request method (GET, POST, etc.) and URL (e.g., https://example.com/wp-json/wp/v2/posts).
  • Use Basic Auth with your WordPress username and the Application Password.
  • Send the request and verify you receive a valid response without authentication errors.

Variations and Additional Tips

  • Revoking Application Passwords: You can revoke any Application Password from the user profile to immediately disable access.
  • Multiple passwords: Generate multiple Application Passwords for different apps or scripts.
  • Custom endpoints: Application Passwords work with custom REST API endpoints that require authentication.
  • HTTPS recommended: Always use HTTPS to protect your credentials during transmission.

Works on

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Control Panels cPanel, Plesk, DirectAdmin
WordPress Versions 5.6 and later (native Application Password support)
PHP Versions PHP 7.0+ (recommended 7.4+)

FAQ

Q1: Can I use Application Passwords with custom REST API endpoints?
Yes. Application Passwords authenticate the user making the request, so any REST API endpoint that requires authentication will accept them.
Q2: What if my Application Password is compromised?
Immediately revoke the compromised Application Password from your user profile. This disables access without affecting your main user password.
Q3: Can Application Passwords be used for non-REST API authentication?
No. They are specifically designed for REST API and XML-RPC authentication.
Q4: How do I encode the Authorization header manually?
Base64 encode the string username:application_password. For example, in PHP: base64_encode('username:app_password').
Q5: Are Application Passwords supported on multisite installations?
Yes, Application Passwords work on multisite, but each user manages their own passwords per site.
…
Developer Snippets

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

Serve static 410 for bots hitting wp‑login & xmlrpc

Posted on August 19, 2025 By Admin No Comments on Serve static 410 for bots hitting wp‑login & xmlrpc

Serve static 410 for bots hitting wp-login & xmlrpc

If your WordPress site is frequently targeted by bots attempting to access wp-login.php and xmlrpc.php, it can lead to increased server load and security risks. A quick and effective way to mitigate this is by serving a static HTTP 410 Gone response to these requests. This tells bots that these endpoints are permanently gone, discouraging repeated access attempts.

Quick Fix

  1. Identify your web server type (Apache, Nginx, LiteSpeed, etc.).
  2. Add the appropriate configuration snippet to serve a 410 response for wp-login.php and xmlrpc.php.
  3. Reload or restart your web server to apply changes.
  4. Test by accessing these URLs and confirm you receive a 410 Gone status.

Why this happens

WordPress sites commonly expose wp-login.php and xmlrpc.php files, which are often targeted by bots for brute-force attacks or exploiting XML-RPC vulnerabilities. While legitimate users need wp-login.php to log in, many sites use alternative login methods or restrict access via plugins or IP whitelisting. Similarly, xmlrpc.php is rarely needed and often disabled to prevent abuse.

Serving a 410 Gone status explicitly informs bots that these endpoints are no longer available, reducing unnecessary server load and improving security posture.

Requirements

  • Access to your web server configuration files or control panel (e.g., Apache .htaccess, Nginx config, LiteSpeed config).
  • Basic knowledge of editing server config files or ability to upload files via FTP/SFTP.
  • Ability to reload or restart your web server after changes.
  • Optional: Backup your configuration files before editing.

Step-by-step

1. Determine your web server

Check your hosting environment or server info to confirm if you use Apache, Nginx, LiteSpeed, or another server.

2. Add configuration to serve 410 for wp-login.php and xmlrpc.php

Apache (.htaccess)

# Serve 410 Gone for wp-login.php and xmlrpc.php
<FilesMatch "^(wp-login.php|xmlrpc.php)$">
  Require all denied
  Redirect gone /
</FilesMatch>

Alternative Apache method:

# Return 410 Gone for wp-login.php and xmlrpc.php
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/(wp-login.php|xmlrpc.php)$ [NC]
RewriteRule ^ - [G,L]

Nginx

# Return 410 Gone for wp-login.php and xmlrpc.php
location ~* ^/(wp-login.php|xmlrpc.php)$ {
    return 410;
}

LiteSpeed

LiteSpeed supports Apache-style .htaccess rules, so use the Apache snippets above.

3. Save and apply changes

After adding the code:

  • For Apache or LiteSpeed, save the .htaccess file in your WordPress root directory.
  • For Nginx, add the snippet to your server block configuration file (e.g., /etc/nginx/sites-available/your-site.conf).
  • Reload or restart your web server:
# Apache
sudo systemctl reload apache2

# Nginx
sudo systemctl reload nginx

# LiteSpeed (depends on setup, often via control panel)

4. Test the response

Use curl or a browser to verify the 410 response:

curl -I https://yourdomain.com/wp-login.php
HTTP/1.1 410 Gone

curl -I https://yourdomain.com/xmlrpc.php
HTTP/1.1 410 Gone

If you see 410 Gone, the configuration works correctly.

Common pitfalls

  • Incorrect file placement: Apache .htaccess must be in the WordPress root directory.
  • Conflicting rules: Other rewrite rules or security plugins may override or conflict with these directives.
  • Server caching: Some hosts use aggressive caching; clear caches after changes.
  • Access needed: If you still need legitimate access to wp-login.php (e.g., for admins), consider restricting by IP instead of serving 410.
  • Control panel overrides: Some managed hosts restrict direct config edits; check with your provider.

Works on

Web Server Supported Notes
Apache Yes Use .htaccess or main config files
Nginx Yes Requires editing server block config
LiteSpeed Yes Supports Apache-style .htaccess rules
cPanel Yes Access .htaccess via File Manager or FTP
Plesk Yes Supports Apache and Nginx config editing

FAQ

1. Will serving 410 break my login or XML-RPC functionality?

Yes, if you or your users rely on wp-login.php or xmlrpc.php, serving 410 will block access. Use this only if you have alternative login methods or have disabled XML-RPC.

2. Can I serve 403 Forbidden instead of 410 Gone?

Yes, 403 is common for blocking access, but 410 explicitly signals the resource is permanently gone, which…

Speed & Security

WooCommerce: Set role‑based pricing (simple example)

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Set role‑based pricing (simple example)

WooCommerce: Set Role-Based Pricing (Simple Example)

If you want to offer different product prices to customers based on their user roles in WooCommerce, this guide will help you implement role-based pricing quickly and effectively. By default, WooCommerce does not support pricing variations by user role, but with a small code snippet, you can customize prices for roles like wholesale customers, subscribers, or any custom role.

Quick Fix: How to Set Role-Based Pricing in WooCommerce

  1. Identify the user roles you want to target.
  2. Add a code snippet to your theme’s functions.php or a custom plugin.
  3. Customize the price adjustments in the snippet according to your roles.
  4. Test by logging in as users with different roles to verify prices change accordingly.

Why This Happens

WooCommerce uses a single price field per product by default, which applies universally to all customers. It does not differentiate pricing based on user roles or customer groups out of the box. To offer role-based pricing, you need to programmatically adjust the displayed price depending on the logged-in user’s role. This is commonly needed for wholesale stores, membership discounts, or tiered pricing strategies.

Requirements

  • WooCommerce installed and activated on your WordPress site.
  • Basic knowledge of editing theme files or creating a simple plugin.
  • Access to your site’s file system or WordPress admin editor.
  • Understanding of user roles in WordPress/WooCommerce.

Step-by-Step: Implement Role-Based Pricing in WooCommerce

  1. Backup your site: Always back up your site before editing code.
  2. Access your theme’s functions.php file: Use FTP, cPanel File Manager, or WordPress Appearance > Theme Editor.
  3. Copy and paste the following code snippet at the end of functions.php:
/**
 * Adjust WooCommerce product price based on user role.
 */
add_filter( 'woocommerce_product_get_price', 'custom_role_based_price', 10, 2 );
add_filter( 'woocommerce_product_get_regular_price', 'custom_role_based_price', 10, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'custom_role_based_price', 10, 2 );

function custom_role_based_price( $price, $product ) {
    if ( is_admin() ) {
        return $price; // Do not change price in admin area
    }

    if ( ! is_user_logged_in() ) {
        return $price; // Only modify price for logged-in users
    }

    $user = wp_get_current_user();
    $roles = (array) $user-roles;

    // Example role-based pricing adjustments
    if ( in_array( 'wholesale_customer', $roles ) ) {
        // 20% discount for wholesale customers
        $price = $price * 0.8;
    } elseif ( in_array( 'subscriber', $roles ) ) {
        // 10% discount for subscribers
        $price = $price * 0.9;
    }

    return $price;
}
  1. Save the file.
  2. Test your changes: Log in as a user with the wholesale_customer role and check product prices. Then test with a subscriber and a non-logged-in user to confirm pricing differences.

Common Pitfalls

  • Editing the wrong file: Always use a child theme or a custom plugin to avoid losing changes during theme updates.
  • Role names mismatch: Ensure the role slugs you use in the code exactly match the roles assigned to users.
  • Price caching: Some caching plugins or server-side caches may serve cached prices. Clear caches after applying changes.
  • Admin area price changes: The snippet avoids changing prices in the admin to prevent confusion during product editing.
  • Not handling variable products: This example works for simple products. Variable products require additional handling.

Works On

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Hosting Panels cPanel, Plesk, DirectAdmin
WordPress Versions 5.0 and above
WooCommerce Versions 3.0 and above

FAQ

Q: Can I add more roles or different discounts?
A: Yes. Simply add more elseif blocks inside the function checking for other roles and set your desired price adjustments.
Q: How do I create a custom user role like wholesale_customer?
A: Use a role management plugin like “User Role Editor” or add code to register a new role with add_role() in WordPress.
Q: Does this work with variable products?
A: This snippet targets simple products. Variable products require hooking into variation prices separately, which involves more complex code.
Q: Will this affect the price stored in the database?
No. This code only changes the price displayed on the front end dynamically. The original product price in the database remains unchanged.
Q: How can I prevent caching issues with role-based pricing?
Exclude pages with dynamic pricing from caching or use cache plugins that support dynamic content based on user roles.
…
WooCommerce How‑tos

Fix WordPress too many redirects (ERR_TOO_MANY_REDIRECTS)

Posted on August 19, 2025 By Admin No Comments on Fix WordPress too many redirects (ERR_TOO_MANY_REDIRECTS)

Fix WordPress too many redirects (ERR_TOO_MANY_REDIRECTS)

If you encounter the ERR_TOO_MANY_REDIRECTS error on your WordPress site, it means your browser is stuck in an infinite redirect loop. This prevents your site from loading properly and frustrates visitors. The quick fix usually involves correcting your WordPress URL settings or your server’s redirect rules.

Quick Fix

  1. Access your WordPress database via phpMyAdmin or a similar tool.
  2. Locate the wp_options table.
  3. Find the siteurl and home entries.
  4. Ensure both URLs use the same protocol (http or https) and domain, for example: https://example.com.
  5. Clear your browser cache and cookies.
  6. If you use a caching or redirect plugin, temporarily disable it.

Alternatively, you can add the following lines to your wp-config.php file to hardcode the URLs:

define('WP_HOME','https://example.com');
define('WP_SITEURL','https://example.com');

Replace https://example.com with your actual site URL.

Why This Happens

The ERR_TOO_MANY_REDIRECTS error occurs when your browser is redirected between URLs repeatedly without reaching the final destination. Common causes include:

  • Mismatched URL settings: WordPress URL settings use HTTP while your site forces HTTPS (or vice versa).
  • Conflicting redirect rules: Server-level redirects (in .htaccess or Nginx config) conflict with WordPress or plugin redirects.
  • Plugin conflicts: Plugins that handle redirects or SSL can cause loops if misconfigured.
  • Incorrect SSL setup: Partial SSL implementation or mixed content issues.

Step-by-step Fix for Nginx and Apache (cPanel/Plesk)

1. Check WordPress URL Settings

Make sure WordPress URLs are consistent and correct.

-- Access your database via phpMyAdmin or command line
SELECT option_name, option_value FROM wp_options WHERE option_name IN ('siteurl', 'home');

-- Update URLs if needed
UPDATE wp_options SET option_value = 'https://example.com' WHERE option_name = 'siteurl';
UPDATE wp_options SET option_value = 'https://example.com' WHERE option_name = 'home';

2. Fix wp-config.php (optional)

Add these lines to enforce correct URLs:

define('WP_HOME','https://example.com');
define('WP_SITEURL','https://example.com');

3. Review Apache .htaccess Redirects (cPanel/Plesk)

Check your .htaccess file in the WordPress root directory for conflicting redirects. A typical WordPress .htaccess looks like this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

If you have HTTPS redirects, ensure they are correct and not looping:

# Redirect HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

4. Review Nginx Redirects

Check your Nginx server block configuration for redirect loops. A proper HTTPS redirect looks like this:

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com www.example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    root /var/www/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }
}

5. Disable Redirect or SSL Plugins

Temporarily deactivate plugins like Really Simple SSL, Redirection, or any caching plugins that might cause redirect loops.

6. Clear Browser and Server Cache

Clear your browser cache and cookies. Also clear any server-side caches (e.g., LiteSpeed cache, Varnish, or CDN caches).

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Hosting control panels: cPanel, Plesk
  • WordPress versions: 4.x, 5.x, 6.x
  • SSL setups: Let’s Encrypt, commercial SSL certificates

FAQ

Q1: Why does ERR_TOO_MANY_REDIRECTS happen only on some browsers?

Browser cache or cookies can cause this error to appear inconsistently. Clearing cache and cookies usually resolves this.

Q2: Can a plugin cause redirect loops?

Yes. Plugins that manage redirects, SSL, or caching can conflict with server redirects or WordPress settings, causing loops.

Q3: How do I know if my SSL is causing the redirect loop?

If your WordPress URLs use HTTPS but your server redirects HTTP to HTTPS incorrectly or partially, it can cause loops. Verify SSL configuration and redirects.

Q4: Is it safe to hardcode URLs in wp-config.php?

Yes, hardcoding WP_HOME and WP_SITEURL is a quick way to fix URL mismatches but should be used carefully to avoid issues during migrations.

Q5: What if none of these fixes work?

Check your server error logs, disable all plugins and switch to a default theme to isolate the issue. Contact your hosting provider if needed.…

Fixes & Errors

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

Disable emojis and embeds to cut requests

Posted on August 19, 2025 By Admin No Comments on Disable emojis and embeds to cut requests

Disable Emojis and Embeds to Cut Requests in WordPress

WordPress loads emoji and embed scripts by default on every page, which adds extra HTTP requests and can slow down your site. Disabling these features reduces unnecessary resource loading, improving page speed and overall performance. This tutorial shows you how to disable emojis and embeds in WordPress quickly and safely.

Quick Fix: Disable Emojis and Embeds in WordPress

  1. Add code snippets to your theme’s functions.php file or a site-specific plugin.
  2. Clear any caching plugins or server caches.
  3. Test your site to confirm emoji and embed scripts are no longer loading.

Why This Happens

WordPress includes built-in support for emojis and oEmbed content (like YouTube videos, Tweets, etc.) by default. This support loads JavaScript and CSS files on every page:

  • Emojis: WordPress loads wp-emoji-release.min.js and related styles to render emojis consistently across browsers.
  • Embeds: WordPress loads wp-embed.min.js to enable embedding content from other sites and to allow your content to be embedded elsewhere.

While useful for many sites, these scripts add extra HTTP requests and increase page size, which can slow down your site, especially on mobile or slow connections.

Step-by-step: Disable Emojis and Embeds in WordPress

Follow these steps to remove emoji and embed scripts from your WordPress site:

  1. Access your theme’s functions.php file or create a site-specific plugin for custom code.
  2. Add the following code snippet:
<?php
// Disable emojis
function disable_wp_emojicons() {
    // Remove emoji scripts and styles
    remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
    remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
    remove_action( 'wp_print_styles', 'print_emoji_styles' );
    remove_action( 'admin_print_styles', 'print_emoji_styles' );

    // Remove from TinyMCE editor
    add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' );

    // Remove emoji CDN hostname from DNS prefetching hints
    add_filter( 'emoji_svg_url', '__return_false' );
}
add_action( 'init', 'disable_wp_emojicons' );

function disable_emojicons_tinymce( $plugins ) {
    if ( is_array( $plugins ) ) {
        return array_diff( $plugins, array( 'wpemoji' ) );
    }
    return array();
}

// Disable embeds
function disable_wp_embeds() {
    // Remove the REST API endpoint
    remove_action( 'rest_api_init', 'wp_oembed_register_route' );

    // Turn off oEmbed auto discovery
    add_filter( 'embed_oembed_discover', '__return_false' );

    // Remove oEmbed-specific JavaScript from front-end and back-end
    remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
    remove_action( 'wp_head', 'wp_oembed_add_host_js' );

    // Remove TinyMCE embed plugin
    add_filter( 'tiny_mce_plugins', 'disable_embeds_tinymce' );

    // Remove oEmbed result caching
    remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
}
add_action( 'init', 'disable_wp_embeds' );

function disable_embeds_tinymce( $plugins ) {
    if ( is_array( $plugins ) ) {
        return array_diff( $plugins, array( 'wpembed' ) );
    }
    return array();
}
?>
  1. Save the file and upload it back to your server (if editing locally).
  2. Clear all caches: If you use caching plugins (e.g., WP Super Cache, W3 Total Cache) or server-level caching, clear those caches to see the changes immediately.
  3. Verify changes: Use your browser’s developer tools (Network tab) to confirm that wp-emoji-release.min.js and wp-embed.min.js are no longer loaded.

Common Pitfalls

  • Editing the wrong file: Always back up your functions.php file before editing. Use a child theme or a site-specific plugin to avoid losing changes during theme updates.
  • Caching issues: Changes might not appear immediately if caching plugins or server caches are active. Clear all caches after applying the code.
  • Plugin conflicts: Some plugins may enqueue emoji or embed scripts independently. You may need to check plugin settings or contact plugin authors.
  • Impact on embeds: Disabling embeds means WordPress won’t automatically convert URLs into embedded content. Use this only if you don’t rely on oEmbed functionality.

Works on

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed, IIS
Control Panels cPanel, Plesk, DirectAdmin
WordPress Versions 4.2 and later (all modern versions)
PHP Versions PHP 5.6 and later

FAQ

Q1: Will disabling emojis break my site’s content?
A1: No, disabling emojis only stops WordPress from loading extra emoji scripts. Emojis will still display using native browser support but may look different on older browsers.
Q2: Can I disable only emojis or only embeds?
A2: Yes. You can remove either the emoji or embed code blocks separately from your functions.php file if you want to disable one but keep the other.
Q3: Will disabling embeds affect Gutenberg blocks?
A3: Yes, disabling embeds removes automatic embed discovery and some embed-related blocks. If you rely heavily on Gutenberg embeds, consider leaving this enabled.
Q4: Is there a plugin to disable emojis and embeds?
A4: Yes, plugins like “Disable Emojis
…
Speed & Security

WooCommerce: Exclude a category from the shop page

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Exclude a category from the shop page

WooCommerce: Exclude a Category from the Shop Page

If you want to hide a specific product category from the main WooCommerce shop page, this tutorial will show you how to quickly exclude that category using a simple code snippet. This is useful when you want to keep certain products available on your site but not visible on the primary shop listing.

Quick Fix

  1. Identify the slug of the product category you want to exclude.
  2. Add a custom function to your theme’s functions.php file or a site-specific plugin.
  3. Use the provided code snippet to modify the main WooCommerce query and exclude the category.
  4. Save changes and refresh the shop page to verify the category is hidden.

Why This Happens

By default, WooCommerce displays all published products on the shop page regardless of their categories. There is no built-in setting to exclude specific categories from appearing on the shop page. To customize this behavior, you need to modify the main product query using WordPress hooks to filter out products belonging to certain categories.

Requirements

  • Access to your WordPress theme files or ability to add custom code via a plugin.
  • Basic knowledge of editing PHP files.
  • WooCommerce installed and active.
  • Identify the category slug you want to exclude (found under Products > Categories).

Step-by-step

  1. Find the category slug:

    Go to WordPress Admin > Products > Categories. Locate the category you want to exclude and note its slug (e.g., hidden-category).

  2. Backup your site:

    Before editing any code, create a backup of your site or use a child theme to avoid losing changes after updates.

  3. Add the exclusion code:

    Edit your theme’s functions.php file or a custom plugin and add the following code snippet. Replace hidden-category with your actual category slug.

    function exclude_category_from_shop_page( $query ) {
        if ( ! is_admin() && $query-is_main_query() && is_shop() ) {
            $tax_query = (array) $query-get( 'tax_query' );
    
            $tax_query[] = array(
                'taxonomy' ='product_cat',
                'field'    ='slug',
                'terms'    =array( 'hidden-category' ), // Replace with your category slug
                'operator' ='NOT IN',
            );
    
            $query-set( 'tax_query', $tax_query );
        }
    }
    add_action( 'pre_get_posts', 'exclude_category_from_shop_page' );
    
  4. Save and test:

    Save the file and visit your WooCommerce shop page. The products from the specified category should no longer appear.

Common Pitfalls

  • Wrong category slug: Using the category name instead of the slug will not work. Always use the slug.
  • Code placed in the wrong file: Adding code to the wrong functions.php file (e.g., parent theme without a child theme) can cause issues on theme updates.
  • Cache issues: If you use caching plugins or server caching, clear caches to see the changes.
  • Conflicting plugins: Some plugins that modify queries may interfere with this code.
  • Not targeting the main query: The code only works if it modifies the main WooCommerce shop query.

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Control panels: cPanel, Plesk, and others
  • WooCommerce versions 3.x and above
  • Any WordPress theme that supports WooCommerce

FAQ

Q: Can I exclude multiple categories at once?
A: Yes. Replace the 'terms' array with multiple slugs, like array('category-one', 'category-two').
Q: Will this hide the category from other pages like archives or widgets?
No. This code only affects the main WooCommerce shop page. You need additional customization to hide categories elsewhere.
Q: Can I exclude categories without editing code?
WooCommerce does not provide a built-in option to exclude categories from the shop page. You can use plugins that offer advanced product filtering or visibility controls if you prefer not to code.
Q: What if the code breaks my site?
Immediately remove the code via FTP or your hosting file manager. Always backup before making changes and test on staging environments.
Q: Does this affect SEO?
Excluding categories from the shop page does not remove them from your site or search engines. Ensure you manage category visibility thoughtfully to avoid duplicate content issues.
…
WooCommerce How‑tos

Posts pagination

Previous 1 2 3 … 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