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

wpcanyon.com

Tag: Rewrite

Fix WordPress posts returning 404 (pages OK)

Posted on August 19, 2025 By Admin No Comments on Fix WordPress posts returning 404 (pages OK)

Fix WordPress posts returning 404 (pages OK)

If your WordPress posts are returning 404 errors while your pages load just fine, it can be a frustrating issue that disrupts your site’s functionality and user experience. The good news is this problem usually stems from permalink or rewrite rule issues, and you can fix it quickly by resetting your permalink structure or adjusting your server configuration.

Quick Fix

  1. Log in to your WordPress admin dashboard.
  2. Go to Settings > Permalinks.
  3. Without changing anything, click the Save Changes button at the bottom.
  4. Check your posts again; the 404 errors should be resolved.

Why this happens

This issue typically occurs because WordPress’s rewrite rules are out of sync or not properly flushed. WordPress uses rewrite rules to map URLs to the correct content. When these rules are corrupted, missing, or not updated, posts URLs can return 404 errors even though pages work fine.

Common causes include:

  • Changing permalink settings without flushing rewrite rules.
  • Server configuration changes or restrictions (e.g., missing .htaccess rules on Apache or incorrect Nginx configuration).
  • Plugin conflicts that modify rewrite rules.
  • File permission issues preventing WordPress from writing to the .htaccess file.

Step-by-step

1. Reset Permalinks in WordPress Dashboard

  1. Navigate to Settings > Permalinks.
  2. Click Save Changes without modifying any settings.

This action forces WordPress to flush and regenerate rewrite rules.

2. Check and Update .htaccess File (Apache)

If resetting permalinks doesn’t fix the issue, verify your .htaccess file contains the correct WordPress rewrite rules.

# 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

Make sure the file is located in your WordPress root directory and is writable by the server.

3. Configure Nginx Rewrite Rules

If you use Nginx, WordPress permalinks require specific rewrite rules in your server configuration. Add or verify the following inside your server block:

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

After updating Nginx config, reload Nginx:

sudo nginx -s reload

4. Check File Permissions

Ensure .htaccess (Apache) or your WordPress root directory files have correct permissions:

chmod 644 .htaccess
chmod 755 /path/to/wordpress/

Incorrect permissions can prevent WordPress from updating rewrite rules.

5. Disable Plugins Temporarily

Some plugins interfere with rewrite rules. Temporarily deactivate all plugins to check if the issue resolves:

wp plugin deactivate --all

If posts work after deactivation, reactivate plugins one by one to identify the culprit.

Works on

Environment Notes
Apache Requires correct .htaccess with WordPress rewrite rules.
Nginx Needs proper try_files directive in server block.
LiteSpeed Compatible with Apache-style .htaccess rules.
cPanel / Plesk Standard hosting control panels; ensure file permissions and rewrite modules enabled.

FAQ

Q: Why do pages work but posts return 404 errors?
A: Pages often use static URLs that don’t rely on rewrite rules as heavily as posts. If rewrite rules are broken, posts URLs break but pages can still load.
Q: Can a plugin cause posts to 404?
A: Yes, plugins that modify URLs or rewrite rules can cause conflicts leading to 404 errors on posts.
Q: How do I flush rewrite rules manually?
A: Besides saving permalinks in the dashboard, you can add flush_rewrite_rules(); in your theme’s functions.php temporarily and then remove it after the rules flush.
Q: What if I don’t have access to .htaccess or Nginx config?
A: Contact your hosting provider to ensure rewrite modules are enabled and configurations are correct.
Q: Does changing permalink structure fix the issue?
A: Sometimes changing and saving a different permalink structure forces rewrite rules to update and resolves 404 errors.
…
Fixes & Errors

Serve WebP in WordPress (with safe JPEG/PNG fallbacks)

Posted on August 19, 2025 By Admin No Comments on Serve WebP in WordPress (with safe JPEG/PNG fallbacks)

Serve WebP in WordPress (with safe JPEG/PNG fallbacks)

Serving WebP images in WordPress improves site speed and reduces bandwidth by delivering smaller, optimized images. However, not all browsers support WebP, so it’s essential to provide safe JPEG/PNG fallbacks. This tutorial shows you how to configure your WordPress site to serve WebP images with fallback support using .htaccess rules.

Quick Fix: Serve WebP with JPEG/PNG Fallbacks via .htaccess

  1. Generate WebP versions of your images (using a plugin or external tool).
  2. Upload WebP images alongside original JPEG/PNG files in your WordPress uploads folder.
  3. Add the provided .htaccess code snippet to your WordPress root directory.
  4. Test your site in different browsers to confirm WebP images load where supported, and JPEG/PNG fallback loads otherwise.

Why This Happens

WebP is a modern image format offering superior compression compared to JPEG and PNG, resulting in faster page loads. However, older browsers or some niche browsers do not support WebP. Without fallback images, unsupported browsers will fail to display images, breaking your site’s appearance.

WordPress by default does not serve WebP images automatically or provide fallbacks. You must configure your server to detect browser support and serve the appropriate image format. Using .htaccess rewrite rules on Apache servers is a common and efficient method to achieve this without changing your theme or plugins.

Requirements

  • Apache web server with mod_rewrite enabled.
  • Access to your WordPress root directory to edit or add a .htaccess file.
  • WebP versions of your images stored alongside original JPEG/PNG files.
  • Basic familiarity with FTP or file manager to upload files and edit .htaccess.

Step-by-step: Serve WebP with JPEG/PNG Fallbacks in WordPress

  1. Create WebP images: Use a plugin like Imagify, EWWW Image Optimizer, or an external tool to generate WebP versions of your JPEG/PNG images. Ensure WebP files are saved in the same folder as the originals.
  2. Backup your current .htaccess file: Before making changes, download a copy of your existing .htaccess file from your WordPress root directory.
  3. Edit your .htaccess file: Add the following code snippet near the top of your .htaccess file, before the WordPress rules block:
# Serve WebP images with JPEG/PNG fallback
<IfModule mod_rewrite.c>
  RewriteEngine On

  # Check if browser supports WebP
  RewriteCond %{HTTP_ACCEPT} image/webp

  # Check if WebP version of the requested image exists
  RewriteCond %{REQUEST_FILENAME}.webp -f

  # Serve WebP image instead
  RewriteRule ^(wp-content/.+.(jpe?g|png))$ $1.webp [T=image/webp,E=accept:1]
</IfModule>

# Add correct content type for WebP images
<IfModule mod_headers.c>
  <FilesMatch ".webp$">
    Header set Content-Type "image/webp"
  </FilesMatch>
</IfModule>

# Ensure WebP images are served with proper caching
<IfModule mod_expires.c>
  ExpiresByType image/webp "access plus 1 month"
</IfModule>
  1. Save and upload the updated .htaccess file.
  2. Clear your site and browser cache.
  3. Test your site: Open your website in a WebP-supporting browser (Chrome, Firefox, Edge) and verify images are served as WebP (use browser developer tools → Network tab → check image content-type). Then test in a non-WebP browser (Safari older versions, IE) to confirm JPEG/PNG images load instead.

Common Pitfalls

  • WebP files missing: The rewrite rule only works if the WebP version exists. Make sure WebP images are generated and uploaded correctly.
  • mod_rewrite not enabled: The rules require Apache’s mod_rewrite module. Confirm it is enabled on your server.
  • Incorrect .htaccess placement: The .htaccess file must be in your WordPress root directory (where wp-config.php is located).
  • Conflicts with other plugins: Some caching or image optimization plugins may conflict with manual .htaccess rules. Test carefully and disable conflicting plugins if needed.
  • Browser caching: Old cached images may prevent you from seeing changes immediately. Clear cache or test in incognito mode.

Works on

Server Compatibility
Apache Fully supported (with mod_rewrite enabled)
Nginx Not applicable (use Nginx config instead)
LiteSpeed Compatible with Apache .htaccess rules
cPanel / Plesk Supported (edit .htaccess via file manager or FTP)

FAQ

Q: How do I generate WebP images for my existing WordPress media library?
A: Use plugins like Imagify or EWWW Image Optimizer that automatically convert and save WebP versions of your images in the uploads folder.
Q: Will this method slow down my website?
A: No. The rewrite rules are efficient and only redirect requests if a WebP version exists and the browser supports it, improving load times by serving smaller images.
Q: What if my server uses
…
Speed & Security

Change taxonomy rewrite slug (without breaking links)

Posted on August 19, 2025 By Admin No Comments on Change taxonomy rewrite slug (without breaking links)

Change Taxonomy Rewrite Slug (Without Breaking Links)

When working with WordPress custom taxonomies, you might want to change the URL slug used in the taxonomy archive URLs. However, changing the rewrite slug directly can break existing links, causing 404 errors and hurting SEO. This tutorial shows you how to safely change a taxonomy rewrite slug without breaking existing links, ensuring smooth transitions and preserving SEO value.

When to Use This

  • You want to update the URL structure of a custom taxonomy for branding or SEO reasons.
  • You need to rename the slug to better reflect content or user expectations.
  • You want to avoid breaking existing links by redirecting old URLs to the new slug.
  • You are comfortable adding code to your theme’s functions.php or creating a mini-plugin.

Quick Fix: Change Taxonomy Rewrite Slug Safely

  1. Update the taxonomy registration with the new rewrite slug.
  2. Flush rewrite rules once after the change.
  3. Add a redirect from the old slug URL to the new slug URL to avoid 404s.
  4. Test the old and new URLs to confirm proper redirection and no broken links.

Why This Happens

WordPress generates URLs for taxonomies based on the rewrite['slug'] parameter set during taxonomy registration. Changing this slug changes the URL structure. However, WordPress does not automatically redirect old URLs to the new ones, so visitors and search engines hitting the old URLs get 404 errors. This breaks links and negatively impacts SEO.

To fix this, you must update the slug in the taxonomy registration and add a redirect from the old slug to the new slug. Flushing rewrite rules ensures WordPress recognizes the new URL structure.

Step-by-Step: Change Taxonomy Rewrite Slug Without Breaking Links

1. Update Taxonomy Registration

Locate where your taxonomy is registered (usually in your theme’s functions.php or a plugin). Change the rewrite['slug'] to the new slug.

function my_custom_taxonomy() {
    $labels = array(
        'name' ='Genres',
        'singular_name' ='Genre',
    );

    $args = array(
        'labels' =$labels,
        'public' =true,
        'rewrite' =array(
            'slug' ='new-genre-slug', // Change this to your new slug
            'with_front' =false,
        ),
        'hierarchical' =true,
    );

    register_taxonomy('genre', 'post', $args);
}
add_action('init', 'my_custom_taxonomy', 0);

2. Flush Rewrite Rules

Flush rewrite rules once after updating the slug. The easiest way is to visit Settings > Permalinks in the WordPress admin and click “Save Changes” without modifying anything.

Alternatively, flush programmatically (only once):

function my_flush_rewrite_rules() {
    my_custom_taxonomy();
    flush_rewrite_rules();
}
add_action('after_switch_theme', 'my_flush_rewrite_rules');

3. Add Redirect from Old Slug to New Slug

Add a redirect rule to send visitors and search engines from the old taxonomy slug URL to the new one. This prevents 404 errors and preserves SEO.

function redirect_old_taxonomy_slug() {
    if (is_tax('genre')) {
        $current_slug = get_query_var('taxonomy');
        $term_slug = get_query_var('term');

        // Old slug URL pattern
        $old_slug = 'old-genre-slug';
        $new_slug = 'new-genre-slug';

        // Check if current URL uses old slug
        if (strpos($_SERVER['REQUEST_URI'], '/' . $old_slug . '/') !== false) {
            $new_url = home_url('/' . $new_slug . '/' . $term_slug . '/');
            wp_redirect($new_url, 301);
            exit;
        }
    }
}
add_action('template_redirect', 'redirect_old_taxonomy_slug');

4. Test URLs

  • Visit an old taxonomy URL (e.g., https://example.com/old-genre-slug/term-name/) and confirm it redirects to the new URL.
  • Visit the new taxonomy URL (e.g., https://example.com/new-genre-slug/term-name/) and confirm it loads correctly.
  • Check for any 404 errors or broken links.

Variations

  • Non-hierarchical taxonomies: The same approach applies; just adjust the taxonomy name and slugs.
  • Multiple taxonomies: Add similar redirect logic for each taxonomy slug change.
  • Using a plugin: Some redirection plugins can handle old-to-new slug redirects without code.
  • Advanced redirects: Use add_rewrite_rule() for complex URL structures.

Works On

Environment Notes
Apache Works seamlessly with mod_rewrite and WordPress permalinks.
Nginx Ensure permalinks are configured correctly; redirects work as expected.
LiteSpeed Compatible with WordPress rewrite rules and redirects.
cPanel / Plesk Standard WordPress setup; no additional config needed.

FAQ

Q1: Can I change the taxonomy slug without adding a redirect?

A: Technically yes, but old URLs will break and return 404 errors, which harms user experience and SEO. Always add redirects when changing slugs.

Q2: How do I find the current taxonomy slug?

A: Check the rewrite['slug'] parameter in your taxonomy registration code or visit the taxonomy archive page and inspect the URL.

Q3: Can I flush rewrite rules programmatically?

A: Yes, but only do it once after changing the slug to avoid performance issues. Use flush_rewrite_rules() inside an activation hook or after your taxonomy registration.

Q4: Will this method work for built-in tax

…
Developer Snippets

Register a custom post type with REST & archive

Posted on August 19, 2025 By Admin No Comments on Register a custom post type with REST & archive

Register a Custom Post Type with REST & Archive in WordPress

When building a WordPress site, you often need to create custom content types beyond posts and pages. Registering a custom post type (CPT) with REST API support and archive pages enables you to manage and display this content efficiently, especially when using headless setups or custom themes. This tutorial shows you how to register a custom post type with REST and archive capabilities using clean, copy-paste-ready code.

When to Use a Custom Post Type with REST & Archive

  • Custom Content Organization: When you want to separate content like portfolios, testimonials, products, or events from regular posts.
  • REST API Integration: If you plan to use the WordPress REST API to fetch or manipulate your custom content in JavaScript apps or external systems.
  • Archive Pages: When you want an automatically generated archive page listing all items of your custom post type.

Quick Fix: Register a Custom Post Type with REST & Archive

  1. Add the provided PHP code snippet to your theme’s functions.php file or create a mini-plugin.
  2. Visit the WordPress admin to confirm the new post type menu appears.
  3. Test the REST API endpoint and archive page.

Why This Happens

By default, WordPress supports posts and pages. To handle other content types, you must register a custom post type using register_post_type(). Enabling 'show_in_rest' =true makes the CPT accessible via the REST API. Setting 'has_archive' =true tells WordPress to generate an archive page for this CPT, allowing visitors to browse all items.

Step-by-step: Registering a Custom Post Type with REST & Archive

Below is a complete example registering a custom post type called book. This CPT supports REST API access and has an archive page.

<?php
function register_book_post_type() {
    $labels = array(
        'name'                  => _x( 'Books', 'Post type general name', 'textdomain' ),
        'singular_name'         => _x( 'Book', 'Post type singular name', 'textdomain' ),
        'menu_name'             => _x( 'Books', 'Admin Menu text', 'textdomain' ),
        'name_admin_bar'        => _x( 'Book', 'Add New on Toolbar', 'textdomain' ),
        'add_new'               => __( 'Add New', 'textdomain' ),
        'add_new_item'          => __( 'Add New Book', 'textdomain' ),
        'new_item'              => __( 'New Book', 'textdomain' ),
        'edit_item'             => __( 'Edit Book', 'textdomain' ),
        'view_item'             => __( 'View Book', 'textdomain' ),
        'all_items'             => __( 'All Books', 'textdomain' ),
        'search_items'          => __( 'Search Books', 'textdomain' ),
        'parent_item_colon'     => __( 'Parent Books:', 'textdomain' ),
        'not_found'             => __( 'No books found.', 'textdomain' ),
        'not_found_in_trash'    => __( 'No books found in Trash.', 'textdomain' ),
        'featured_image'        => _x( 'Book Cover Image', 'Overrides the “Featured Image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'set_featured_image'    => _x( 'Set cover image', 'Overrides the “Set featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'remove_featured_image' => _x( 'Remove cover image', 'Overrides the “Remove featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'use_featured_image'    => _x( 'Use as cover image', 'Overrides the “Use as featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'archives'              => _x( 'Book archives', 'The post type archive label used in nav menus. Default “Post Archives”. Added in 4.4', 'textdomain' ),
        'insert_into_item'      => _x( 'Insert into book', 'Overrides the “Insert into post”/”Insert into page” phrase (used when inserting media into a post). Added in 4.4', 'textdomain' ),
        'uploaded_to_this_item' => _x( 'Uploaded to this book', 'Overrides the “Uploaded to this post”/”Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4', 'textdomain' ),
        'filter_items_list'     => _x( 'Filter books list', 'Screen reader text for the filter links heading on the post type listing screen. Default “Filter posts list”/”Filter pages list”. Added in 4.4', 'textdomain' ),
        'items_list_navigation' => _x( 'Books list navigation', 'Screen reader text for the pagination heading on the post type listing screen. Default “Posts list navigation”/”Pages list navigation”. Added in 4.4', 'textdomain' ),
        'items_list'            => _x( 'Books list', 'Screen reader text for the items list heading on the post type listing screen. Default “Posts list”/”Pages list”. Added in 4.4', 'textdomain' ),
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'books' ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => 5,
        'menu_icon'          => 'dashicons-book',
        'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
        'show_in_rest'       => true,
        'rest_base'          => 'books',
        'rest_controller_class' => 'WP_REST_Posts_Controller',
    );

    register_post_type( 'book', $args );
}
add_action( 'init', 'register_book_post_type' );

How to Add This Code

You can add the above code in two ways:

  1. functions.php:
…
Developer Snippets

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

    Also by the maker of MySurveyReviews.com