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

wpcanyon.com

Category: Developer Snippets

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

Enqueue scripts/styles the right way (with dependencies)

Posted on August 19, 2025 By Admin No Comments on Enqueue scripts/styles the right way (with dependencies)

Enqueue Scripts/Styles the Right Way (with Dependencies)

Properly enqueueing scripts and styles in WordPress is essential for ensuring your site loads efficiently, avoids conflicts, and respects dependencies. This tutorial explains how to enqueue scripts and styles the right way, including managing dependencies, and provides practical code examples you can copy and paste into your theme or plugin.

When to Use Proper Enqueueing

  • Adding custom JavaScript or CSS to your theme or plugin.
  • Loading third-party libraries like jQuery, Bootstrap, or Font Awesome.
  • Ensuring scripts/styles load only when needed to optimize performance.
  • Preventing conflicts by managing script dependencies and versions.

Quick Fix: Enqueue Scripts Properly in WordPress

  1. Use wp_enqueue_script() and wp_enqueue_style() functions.
  2. Hook your enqueue functions to wp_enqueue_scripts (frontend) or admin_enqueue_scripts (admin area).
  3. Specify dependencies as an array to ensure correct load order.
  4. Use versioning to bust cache when files update.
  5. Place your enqueue code in functions.php or a custom plugin.

Why This Happens

WordPress uses a queue system to manage scripts and styles. If you add scripts/styles incorrectly (e.g., hardcoding in header/footer), you risk:

  • Loading scripts multiple times or out of order.
  • Conflicts between plugins or themes using the same libraries.
  • Broken dependencies causing JavaScript errors.
  • Performance issues due to unnecessary or duplicated loads.

Using WordPress’s enqueue functions ensures scripts and styles load once, in the right order, and only when needed.

Step-by-Step: Enqueue Scripts and Styles with Dependencies

Below is a complete example showing how to enqueue a custom JavaScript file and a CSS file with dependencies on jQuery and a third-party CSS library.

<?php
function mytheme_enqueue_assets() {
    // Enqueue a CSS library (e.g., Bootstrap) from CDN
    wp_enqueue_style(
        'bootstrap-css', // Handle
        'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css', // Source
        array(), // No dependencies
        '5.3.0' // Version
    );

    // Enqueue a custom stylesheet that depends on Bootstrap CSS
    wp_enqueue_style(
        'mytheme-style',
        get_template_directory_uri() . '/css/custom-style.css',
        array('bootstrap-css'), // Dependency
        '1.0.0'
    );

    // Enqueue jQuery (WordPress includes jQuery by default)
    wp_enqueue_script('jquery');

    // Enqueue a custom JavaScript file that depends on jQuery
    wp_enqueue_script(
        'mytheme-script',
        get_template_directory_uri() . '/js/custom-script.js',
        array('jquery'), // Dependency
        '1.0.0',
        true // Load in footer
    );
}
add_action('wp_enqueue_scripts', 'mytheme_enqueue_assets');
?>

Explanation:

  • wp_enqueue_style() loads CSS files. The third parameter is an array of dependencies.
  • wp_enqueue_script() loads JavaScript files. The third parameter is dependencies, the fourth is version, and the fifth controls whether to load in footer.
  • Using get_template_directory_uri() points to your theme folder.
  • Hooking into wp_enqueue_scripts ensures scripts/styles load on the frontend.

Add via functions.php or Mini-Plugin

You can add the above code directly to your theme’s functions.php file or create a mini-plugin for portability.

<?php
/*
Plugin Name: My Custom Enqueue Plugin
Description: Properly enqueue scripts and styles with dependencies.
Version: 1.0
Author: Your Name
*/

function myplugin_enqueue_assets() {
    wp_enqueue_style('bootstrap-css', 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css', array(), '5.3.0');
    wp_enqueue_style('myplugin-style', plugin_dir_url(__FILE__) . 'css/custom-style.css', array('bootstrap-css'), '1.0.0');
    wp_enqueue_script('jquery');
    wp_enqueue_script('myplugin-script', plugin_dir_url(__FILE__) . 'js/custom-script.js', array('jquery'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'myplugin_enqueue_assets');
?>

Testing Your Enqueued Scripts and Styles

  1. Clear your browser cache or use incognito mode.
  2. View your site’s source code (Ctrl+U or right-click → View Page Source).
  3. Search for your script and style handles (e.g., mytheme-style or mytheme-script).
  4. Check the order of scripts/styles to confirm dependencies load first.
  5. Open browser developer tools (Console tab) to ensure no JavaScript errors.

Variations

Use Case Example Notes
Load scripts only on specific pages
if (is_page('contact')) {
    wp_enqueue_script('contact-form', ...);
}
Improves performance by limiting loads.
Enqueue admin scripts/styles
add_action('admin_enqueue_scripts', 'my_admin_assets');
function my_admin_assets() {
    wp_enqueue_style('admin-style', ...);
}
Loads assets only in WordPress admin area.
Localize scripts for passing PHP data
wp_localize_script('mytheme-script', 'myData', array(
    'ajaxUrl' => admin_url('admin-ajax.php'),
));
Passes dynamic data to JavaScript safely.

Works On

  • Web servers: Apache, Nginx, LiteSpeed
…
Developer Snippets

Custom login logo + styles (theme‑agnostic)

Posted on August 19, 2025 By Admin No Comments on Custom login logo + styles (theme‑agnostic)

Custom Login Logo + Styles (Theme-Agnostic)

Many WordPress site owners want to replace the default WordPress login logo with their own branding. This is especially useful for client projects, membership sites, or any scenario where a custom branded login experience is desired. The challenge is to do this in a way that works regardless of the active theme — a theme-agnostic solution.

This tutorial shows you how to add a custom login logo and styles using code that you can place in your functions.php file or a mini-plugin. This method ensures your customizations persist even if you switch themes.

When to Use a Custom Login Logo + Styles

  • You want to replace the default WordPress logo on the login page with your own logo.
  • You need to customize the login page’s look and feel without relying on theme support.
  • You want a lightweight, code-based solution instead of a plugin.
  • You want to maintain branding consistency for clients or users.

Quick Fix: Add Custom Login Logo and Styles

  1. Prepare your custom logo image (recommended size: 320×80 pixels, PNG or SVG).
  2. Upload the logo to your theme or child theme folder, or use the WordPress Media Library.
  3. Add the provided PHP code snippet to your functions.php file or create a mini-plugin.
  4. Test the login page to verify the logo and styles appear correctly.

Why This Happens

By default, WordPress uses its own logo on the login page, which is hardcoded in the login form markup. To customize it, you need to hook into WordPress actions and filters to override the default styles and replace the logo URL. Since the login page is outside the theme templates, theme styles don’t apply here, so you must enqueue your own CSS or output inline styles via hooks.

Step-by-Step: Custom Login Logo + Styles Code

Below is a complete code snippet that:

  • Replaces the login logo with your custom image.
  • Adjusts the logo size and login form styles.
  • Changes the logo link URL and title attribute.
<?php
// Hook to customize login logo and styles
function custom_login_logo() {
    // URL to your custom logo - adjust path as needed
    $logo_url = get_stylesheet_directory_uri() . '/images/custom-login-logo.png';

    // Output custom CSS for login page
    echo '<style type="text/css">
        #login h1 a, .login h1 a {
            background-image: url(' . esc_url($logo_url) . ');
            background-size: contain;
            width: 320px;
            height: 80px;
            margin: 0 auto 25px;
        }
        /* Optional: customize login form background and button */
        body.login {
            background-color: #f1f1f1;
        }
        .login form {
            background: #fff;
            border: 1px solid #ddd;
            padding: 26px 24px;
            box-shadow: 0 1px 3px rgba(0,0,0,.13);
        }
        .wp-core-ui .button-primary {
            background: #0073aa;
            border-color: #006799;
            box-shadow: none;
            text-shadow: none;
        }
        .wp-core-ui .button-primary:hover {
            background: #006799;
            border-color: #005177;
        }
    </style>';
}
add_action('login_enqueue_scripts', 'custom_login_logo');

// Change the logo link URL to your homepage or custom URL
function custom_login_logo_url() {
    return home_url();
}
add_filter('login_headerurl', 'custom_login_logo_url');

// Change the logo title attribute on hover
function custom_login_logo_url_title() {
    return get_bloginfo('name');
}
add_filter('login_headertext', 'custom_login_logo_url_title');
?>

How to Add This Code

You have two main options:

  1. Add to your theme’s functions.php file:
    Open functions.php in your active theme or child theme folder and paste the code at the bottom. Save and upload.
  2. Create a mini-plugin:
    Create a new file named custom-login-logo.php in wp-content/plugins/ with the following header and the code above:
    <?php
    /*
    Plugin Name: Custom Login Logo
    Description: Adds a custom login logo and styles.
    Version: 1.0
    Author: Your Name
    */
    

    Then paste the code snippet below the header. Activate the plugin via the WordPress admin.

Testing Your Custom Login Logo

  1. Clear your browser cache or open a private/incognito window.
  2. Visit https://yourdomain.com/wp-login.php or https://yourdomain.com/wp-admin/.
  3. Verify that your custom logo appears instead of the default WordPress logo.
  4. Check the logo link points to your homepage and the title attribute shows your site name.
  5. Adjust CSS in the code snippet if the logo size or positioning needs tweaking.

Variations and Enhancements

  • Use an SVG logo: Upload an SVG file and update the URL accordingly. Ensure your server supports SVG display.
  • Load logo from Media Library: Replace $logo_url with the full URL of an image uploaded via Media Library.
  • Customize login page background: Add more CSS rules inside the <style> block to change background colors, fonts, or add custom messages.
  • Use external CSS file: Instead of inline styles, enqueue a custom CSS file using wp_enqueue_style hooked to login_enqueue_scripts.
  • Change login form elements: Use additional hooks like login_form or login_footer to add custom HTML or scripts.

Works On

<

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed, IIS
Control Panels cPanel, Plesk, DirectAdmin
…
Developer Snippets

Add classes to previous/next post links

Posted on August 19, 2025 By Admin No Comments on Add classes to previous/next post links

Add Classes to Previous/Next Post Links in WordPress

When navigating between posts in WordPress, the default previous_posts_link() and next_posts_link() functions output simple links without custom classes. Adding CSS classes to these links allows you to style them consistently with your theme or add JavaScript hooks. This tutorial shows you how to add classes to previous and next post links in WordPress quickly and cleanly.

When to Use This

  • You want to style the previous/next post links with custom CSS.
  • You need to add JavaScript event listeners or animations targeting these links.
  • You want to integrate the links into a design system or framework that requires specific classes.
  • You prefer semantic and maintainable code without editing theme template files directly.

Quick Fix: Add Classes to Previous/Next Post Links

  1. Create a custom function to output the previous post link with a class.
  2. Create a custom function to output the next post link with a class.
  3. Replace the default previous_posts_link() and next_posts_link() calls in your theme with these custom functions.
  4. Alternatively, add filters or override the functions via functions.php or a mini-plugin.

Why This Happens

By default, WordPress’s previous_posts_link() and next_posts_link() functions generate simple anchor tags without any CSS classes. This is because these functions prioritize simplicity and backward compatibility. They accept a link text parameter but do not have a built-in way to add classes or other attributes directly.

To add classes, you need to either:

  • Manually output the links using get_previous_posts_link() and get_next_posts_link() and wrap them with your own markup.
  • Use filters or custom functions to modify the output.

Step-by-Step: Add Classes to Previous/Next Post Links

Below is a clean and reusable approach that you can add to your theme’s functions.php file or a custom mini-plugin.

<?php
// Custom function to output previous posts link with class
function my_previous_posts_link_with_class( $label = 'Previous Page', $class = 'prev-post-link' ) {
    $link = get_previous_posts_link( $label );
    if ( $link ) {
        // Add class attribute to the anchor tag
        $link = str_replace( '<a href=', '<a class="' . esc_attr( $class ) . '" href=', $link );
        echo $link;
    }
}

// Custom function to output next posts link with class
function my_next_posts_link_with_class( $label = 'Next Page', $class = 'next-post-link' ) {
    $link = get_next_posts_link( $label );
    if ( $link ) {
        // Add class attribute to the anchor tag
        $link = str_replace( '<a href=', '<a class="' . esc_attr( $class ) . '" href=', $link );
        echo $link;
    }
}
?>

Then, replace your theme’s default calls in the template files (usually index.php, archive.php, or home.php) like this:

<?php
// Instead of previous_posts_link();
my_previous_posts_link_with_class( '← Older Posts', 'btn btn-primary prev-link' );

// Instead of next_posts_link();
my_next_posts_link_with_class( 'Newer Posts →', 'btn btn-primary next-link' );
?>

Adding via a Mini-Plugin

If you prefer not to modify your theme’s functions.php, create a mini-plugin:

<?php
/*
Plugin Name: Custom Previous/Next Posts Link Classes
Description: Adds CSS classes to previous and next posts links.
Version: 1.0
Author: Your Name
*/

function my_previous_posts_link_with_class( $label = 'Previous Page', $class = 'prev-post-link' ) {
    $link = get_previous_posts_link( $label );
    if ( $link ) {
        $link = str_replace( '<a href=', '<a class="' . esc_attr( $class ) . '" href=', $link );
        echo $link;
    }
}

function my_next_posts_link_with_class( $label = 'Next Page', $class = 'next-post-link' ) {
    $link = get_next_posts_link( $label );
    if ( $link ) {
        $link = str_replace( '<a href=', '<a class="' . esc_attr( $class ) . '" href=', $link );
        echo $link;
    }
}
?>

Activate this plugin and update your theme templates as shown above.

Testing Your Changes

  1. Clear any caching plugins or server caches.
  2. Visit an archive page or the blog homepage where previous/next post links appear.
  3. Inspect the previous and next post links using your browser’s developer tools.
  4. Verify that the anchor tags now include the classes you specified (e.g., btn btn-primary prev-link).
  5. Apply CSS styles targeting these classes to confirm styling works.

Variations and Enhancements

  • Customizing Labels: Pass custom link text to the functions, e.g., my_previous_posts_link_with_class('Older Posts', 'custom-class').
  • Adding Multiple Classes: Pass space-separated classes as the second parameter.
  • Using Filters: Hook into previous_posts_link_attributes and next_posts_link_attributes filters (available in newer WP versions) to add classes.
  • Accessibility: Add ARIA attributes or roles by modifying the output string similarly.
  • Button Markup: Wrap the links in <nav> or <div> containers with classes for better layout control.

Works On

<

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Control Panels cPanel, Plesk, DirectAdmin
…
Developer Snippets

Shortcode: list posts by tag with excerpt

Posted on August 19, 2025 By Admin No Comments on Shortcode: list posts by tag with excerpt

Shortcode: List Posts by Tag with Excerpt in WordPress

If you want to display a list of posts filtered by a specific tag along with their excerpts anywhere on your WordPress site, using a shortcode is a practical and flexible solution. This tutorial shows you how to create a custom shortcode that lists posts by tag with excerpts, so you can easily embed it in posts, pages, or widgets.

When to Use This Shortcode

  • You want to highlight related content by tag on a page or post.
  • You need a dynamic list of posts filtered by tags without manually updating links.
  • You want to show post excerpts alongside titles for better context.
  • You prefer a shortcode solution that can be reused and customized easily.

Quick Fix: Create a Shortcode to List Posts by Tag with Excerpt

  1. Add the provided PHP code to your theme’s functions.php file or create a mini-plugin.
  2. Use the shortcode [posts_by_tag tag="your-tag-slug" posts="5"] in your content.
  3. Adjust parameters like tag slug and number of posts as needed.
  4. Test the shortcode on a page or post to verify output.

Why This Happens

WordPress does not have a built-in shortcode to list posts filtered by tag with excerpts. The default shortcodes like [recent_posts] or widgets do not provide flexible tag filtering combined with excerpts. Creating a custom shortcode leverages WordPress’s WP_Query class to fetch posts by tag and outputs them in a clean, reusable format.

Step-by-Step: Add the Shortcode Code

Below is the complete PHP code for the shortcode. It accepts two attributes:

  • tag: The slug of the tag to filter posts by (required).
  • posts: Number of posts to display (optional, default is 5).
<?php
// Shortcode to list posts by tag with excerpt
function shortcode_list_posts_by_tag_with_excerpt($atts) {
    // Set default attributes and merge with user input
    $atts = shortcode_atts(
        array(
            'tag' => '',        // Tag slug to filter by
            'posts' => 5       // Number of posts to show
        ), 
        $atts, 
        'posts_by_tag'
    );

    // Sanitize inputs
    $tag_slug = sanitize_text_field($atts['tag']);
    $posts_per_page = intval($atts['posts']);
    if ($posts_per_page <= 0) {
        $posts_per_page = 5;
    }

    if (empty($tag_slug)) {
        return '<p>Please provide a tag slug in the shortcode attribute.</p>';
    }

    // Query posts by tag
    $query_args = array(
        'tag' => $tag_slug,
        'posts_per_page' => $posts_per_page,
        'post_status' => 'publish',
        'ignore_sticky_posts' => true,
    );

    $query = new WP_Query($query_args);

    if (!$query->have_posts()) {
        return '<p>No posts found for tag: ' . esc_html($tag_slug) . '</p>';
    }

    // Start output buffering
    ob_start();

    echo '<ul class="posts-by-tag-list">';

    while ($query->have_posts()) {
        $query->the_post();
        echo '<li>';
        echo '<a href="' . esc_url(get_permalink()) . '">' . esc_html(get_the_title()) . '</a>';
        echo '<p class="post-excerpt">' . esc_html(get_the_excerpt()) . '</p>';
        echo '</li>';
    }

    echo '</ul>';

    wp_reset_postdata();

    return ob_get_clean();
}
add_shortcode('posts_by_tag', 'shortcode_list_posts_by_tag_with_excerpt');
?>

How to Add This Code

  1. Via functions.php: Open your active theme’s functions.php file and paste the above code at the end.
  2. Via Mini-Plugin: Create a new file named posts-by-tag-shortcode.php in wp-content/plugins/ with the following header and the code above:
<?php
/*
Plugin Name: Posts By Tag Shortcode
Description: Adds a shortcode to list posts by tag with excerpts.
Version: 1.0
Author: Your Name
*/
 
// Paste the shortcode function code here
?>

Then activate the plugin from the WordPress admin.

Testing the Shortcode

  1. Create or edit a post/page where you want to display the list.
  2. Insert the shortcode with your desired tag slug and number of posts, for example:
[posts_by_tag tag="news" posts="3"]

This will display the 3 most recent posts tagged with news, showing their titles linked to the posts and excerpts below.

Variations and Customizations

  • Change number of posts: Adjust the posts attribute, e.g. posts="10".
  • Style output: Add CSS targeting .posts-by-tag-list and .post-excerpt classes.
  • Show full content: Replace get_the_excerpt() with get_the_content() in the code.
  • Order posts: Modify $query_args to include 'orderby' => 'date' or other parameters.
  • Multiple tags: Extend the shortcode to accept comma-separated tags by adjusting the query.

Works On

Environment Notes
Apache, Nginx, LiteSpeed Compatible with all standard web servers running WordPress.
cPanel, Plesk Works on hosting control panels with standard WordPress installations.
PHP
…
Developer Snippets

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

WP_Query: exclude a category (and paginated archives)

Posted on August 19, 2025 By Admin No Comments on WP_Query: exclude a category (and paginated archives)

WP_Query: Exclude a Category (and Paginated Archives)

If you want to display posts on your WordPress site but exclude one or more categories — including on paginated archive pages — the WP_Query class is your go-to solution. This tutorial shows you how to exclude categories properly, ensuring pagination works seamlessly without showing posts from unwanted categories.

When to Use This

  • You want to customize your blog or archive pages to hide posts from specific categories.
  • You need to exclude categories on paginated archive pages without breaking pagination.
  • You want to create custom loops or queries that omit certain categories.

Quick Fix: Exclude Categories in WP_Query

  1. Use the category__not_in parameter in WP_Query to exclude categories by ID.
  2. Ensure pagination parameters are correctly passed to maintain paginated archives.
  3. Add the code snippet to your theme’s functions.php or a custom plugin.
  4. Test on archive and paginated pages to confirm excluded categories don’t appear.

Why This Happens

By default, WordPress queries include posts from all categories unless filtered. Using category__not_in tells WordPress to exclude posts assigned to specific category IDs. However, if pagination is not handled correctly, excluding categories can cause pagination to break or display unexpected results because the total post count changes.

Properly passing the current page number and using WP_Query with exclusion parameters ensures WordPress calculates pagination based on the filtered posts, maintaining correct page counts and navigation.

Step-by-Step: Exclude a Category with Pagination Support

  1. Identify the category ID(s) you want to exclude. You can find this in the WordPress admin under Posts → Categories. Hover over a category name and note the ID from the URL (e.g., tag_ID=5).
  2. Create a custom query using WP_Query with the category__not_in parameter and pagination support.
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

$args = array(
    'post_type'      => 'post',
    'posts_per_page' => 10,
    'paged'          => $paged,
    'category__not_in' => array(5), // Replace 5 with your category ID(s)
);

$custom_query = new WP_Query( $args );

if ( $custom_query->have_posts() ) :
    while ( $custom_query->have_posts() ) : $custom_query->the_post();
        the_title('<h2>', '</h2>');
        the_excerpt();
    endwhile;

    // Pagination
    echo paginate_links( array(
        'total'   => $custom_query->max_num_pages,
        'current' => $paged,
    ) );

    wp_reset_postdata();
else :
    echo '<p>No posts found.</p>';
endif;
?>

Add via functions.php or Mini-Plugin

You can add the above code directly in a custom page template or inside a shortcode function for easier reuse. Here is an example shortcode you can add to your theme’s functions.php or a small plugin file:

<?php
function exclude_category_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'exclude' => '', // comma-separated category IDs
        'posts_per_page' => 5,
    ), $atts, 'exclude_category' );

    $exclude_ids = array_map( 'intval', explode( ',', $atts['exclude'] ) );
    $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => intval( $atts['posts_per_page'] ),
        'paged'          => $paged,
        'category__not_in' => $exclude_ids,
    );

    $query = new WP_Query( $args );

    ob_start();

    if ( $query->have_posts() ) :
        while ( $query->have_posts() ) : $query->the_post();
            echo '<h2>' . get_the_title() . '</h2>';
            echo get_the_excerpt();
        endwhile;

        echo paginate_links( array(
            'total'   => $query->max_num_pages,
            'current' => $paged,
        ) );

        wp_reset_postdata();
    else :
        echo '<p>No posts found.</p>';
    endif;

    return ob_get_clean();
}
add_shortcode( 'exclude_category', 'exclude_category_shortcode' );
?>

Use the shortcode in posts or pages like this:

[exclude_category exclude="5,7" posts_per_page="10"]

Testing

  1. Place the code in your theme or use the shortcode on a page.
  2. Visit the page and verify posts from the excluded categories do not appear.
  3. Navigate to paginated pages (e.g., /page/2/) and confirm pagination works and excluded categories remain hidden.
  4. Check for any 404 errors or empty pages and adjust posts_per_page or category IDs if needed.

Variations

  • Exclude multiple categories: Pass multiple IDs in the array, e.g., 'category__not_in' => array(5, 7, 9).
  • Exclude by slug: Use tax_query instead of category__not_in for more complex queries.
  • Exclude categories on main blog page: Use the pre_get_posts action hook to modify the main query.

Works on

Environment Notes
Apache Fully compatible; standard WordPress setup.
Nginx Works as expected; ensure permalinks are configured correctly.
LiteSpeed Compatible; no special configuration needed.
…
Developer Snippets

Add a CSS class to the current menu item (wp_nav_menu)

Posted on August 19, 2025 By Admin No Comments on Add a CSS class to the current menu item (wp_nav_menu)

Add a CSS Class to the Current Menu Item (wp_nav_menu)

When working with WordPress menus, you might want to highlight the current menu item by adding a custom CSS class. This is useful for styling purposes, such as changing the color or font of the active menu item to improve user navigation experience. WordPress automatically adds some classes like current-menu-item, but sometimes you need a custom class for more precise control or specific styling frameworks.

Quick Fix: Add a Custom CSS Class to the Current Menu Item

  1. Open your theme’s functions.php file or create a mini-plugin.
  2. Add a filter to nav_menu_css_class to append your custom class to the current menu item.
  3. Save and test the menu on the front end to confirm the class is added.

Why This Happens

WordPress’s wp_nav_menu() function generates menu HTML and automatically adds classes like current-menu-item to the active menu item. However, these default classes might not fit your CSS framework or design system. By hooking into the nav_menu_css_class filter, you can add or modify classes dynamically, giving you full control over menu item styling.

Step-by-Step: Add a Custom CSS Class to the Current Menu Item

  1. Open your WordPress theme folder and locate the functions.php file.
  2. Add the following code snippet to the end of the file:
function add_custom_class_to_current_menu_item($classes, $item) {
    if (in_array('current-menu-item', $classes)) {
        $classes[] = 'my-custom-current-class'; // Replace with your custom class name
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_class_to_current_menu_item', 10, 2);
  1. Save the file and upload it back to your server if editing locally.
  2. Visit your website and inspect the menu. The current menu item should now have the my-custom-current-class added alongside the default classes.

Alternative: Create a Mini-Plugin for This

If you prefer not to modify your theme’s functions.php, create a mini-plugin instead:

<?php
/*
Plugin Name: Custom Current Menu Class
Description: Adds a custom CSS class to the current menu item.
Version: 1.0
Author: Your Name
*/

function add_custom_class_to_current_menu_item($classes, $item) {
    if (in_array('current-menu-item', $classes)) {
        $classes[] = 'my-custom-current-class'; // Replace with your custom class name
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_class_to_current_menu_item', 10, 2);

Save this as custom-current-menu-class.php and upload it to wp-content/plugins/. Activate it from the WordPress admin dashboard.

Testing

  • Clear any caching plugins or server cache to see changes immediately.
  • Open your site in a browser and navigate to different pages.
  • Use browser developer tools (Inspect Element) to verify the custom class appears on the current menu item.
  • Apply CSS rules targeting .my-custom-current-class to confirm styling changes.

Variations

  • Add class to current menu ancestor: To highlight parent items of the current page, check for current-menu-ancestor or current-menu-parent classes.
  • Different class names: Change my-custom-current-class to any class name that fits your CSS naming conventions.
  • Multiple classes: Append multiple classes by adding more entries to the $classes array.
  • Conditional logic: Add classes only for specific menus by checking $item-menu-slug or $item-menu_item_parent.
function add_custom_class_to_current_menu_item($classes, $item, $args) {
    if (in_array('current-menu-item', $classes)) {
        $classes[] = 'my-custom-current-class';
    }
    if (in_array('current-menu-ancestor', $classes)) {
        $classes[] = 'my-custom-ancestor-class';
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_class_to_current_menu_item', 10, 3);

Works On

Environment Notes
Apache Fully compatible; no special configuration needed.
Nginx Works without issues; ensure PHP is properly configured.
LiteSpeed Compatible; same as Apache.
cPanel / Plesk Works as expected; edit files via File Manager or FTP.
Any WordPress Theme Compatible with all themes that use wp_nav_menu().

FAQ

Q: Why doesn’t my custom class show up on the current menu item?
A: Make sure you cleared caches and that your theme uses wp_nav_menu(). Also, confirm the filter is added correctly and no syntax errors exist.
Q: Can I add this class only to a specific menu?
A: Yes. Use the third parameter $args in the filter callback to check $args-theme_location or $args-menu and conditionally add classes.
Q: How do I style the new class?
A: Add CSS rules targeting your custom class in your theme’s stylesheet or customizer. For example: .my-custom-current-class { color: red; }
Q: Will this work with custom walker classes?
A: Yes, but if your custom walker overrides menu classes, ensure it merges or respects the classes added by this filter.
…
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