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

wpcanyon.com

Tag: Theme

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

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

Adding Classes to body_class() in WordPress

Posted on August 19, 2025 By Admin No Comments on Adding Classes to body_class() in WordPress

Adding Classes to body_class() in WordPress

When building or customizing WordPress themes, you often need to add custom CSS classes to the <body> tag for styling or JavaScript targeting. WordPress provides the body_class() function to output classes dynamically, but sometimes you want to add your own classes programmatically. This tutorial explains how to add classes to body_class() in WordPress the right way, with updated code for modern WordPress, including block themes and Gutenberg considerations.

Quick Fix: How to Add Classes to body_class()

  1. Open your theme’s functions.php file or create a small plugin.
  2. Add a filter to body_class that appends your custom classes.
  3. Test by viewing your site’s source code and verifying the <body> tag classes.

Why This Happens

The body_class() function outputs an array of CSS classes for the <body> tag, reflecting the current page context (e.g., home, single post, category). By default, WordPress controls these classes, but developers often need to add custom classes for additional styling or scripting purposes. Directly editing theme templates to hardcode classes is not recommended because it breaks flexibility and maintainability. Instead, WordPress provides a filter hook body_class to safely modify or add classes.

When to Use Custom Classes in body_class()

  • Adding page-specific or user-specific CSS hooks.
  • Targeting custom post types or taxonomies with CSS or JS.
  • Adding classes based on user roles or login status.
  • Conditionally styling parts of your theme without modifying templates.

Updated Code for Modern WordPress

Since WordPress 5.0+ and the rise of block themes and Gutenberg, the method to add classes remains the same but you should ensure your code is compatible with block-based templates and full site editing.

Here is the recommended approach using the body_class filter:

function my_custom_body_classes( $classes ) {
    // Add a custom class
    $classes[] = 'my-custom-class';

    // Conditionally add a class on the homepage
    if ( is_front_page() ) {
        $classes[] = 'front-page-class';
    }

    // Add class if user is logged in
    if ( is_user_logged_in() ) {
        $classes[] = 'logged-in-user';
    }

    return $classes;
}
add_filter( 'body_class', 'my_custom_body_classes' );

How to Add Custom Classes via functions.php or a Small Plugin

  1. Via functions.php:

    Open your active theme’s functions.php file and paste the code snippet above at the end of the file.

  2. Via a small plugin:

    Create a new PHP file in wp-content/plugins/ named custom-body-classes.php with the following content:

    <?php
        /*
        Plugin Name: Custom Body Classes
        Description: Adds custom classes to the body tag.
        Version: 1.0
        Author: Your Name
        */
    
        function my_custom_body_classes( $classes ) {
            $classes[] = 'my-custom-class';
            if ( is_front_page() ) {
                $classes[] = 'front-page-class';
            }
            if ( is_user_logged_in() ) {
                $classes[] = 'logged-in-user';
            }
            return $classes;
        }
        add_filter( 'body_class', 'my_custom_body_classes' );
        

    Then activate this plugin from the WordPress admin.

Step-by-Step Test

  1. Add the code snippet to your functions.php or activate the plugin.
  2. Clear any caches if you use caching plugins or server caching.
  3. Visit your homepage and view the page source (right-click > View Page Source).
  4. Locate the <body> tag and verify your custom classes appear, e.g., my-custom-class and front-page-class.
  5. Log in to your WordPress admin and refresh the page to confirm logged-in-user class appears.
  6. Test on other pages to verify classes change according to conditions.

Block Themes & Gutenberg Notes

Block themes and the Full Site Editing (FSE) experience introduced in WordPress 5.9+ do not change how body_class() works. The body_class filter remains the standard way to add classes. However, some block themes may use different templates or wrappers, so ensure your theme calls body_class() in the <body> tag.

For block themes, you can also add classes via the theme.json file or custom block styles, but for global body classes, the filter method is still best.

Common Pitfalls

  • Not returning the modified classes array: Always return the modified $classes array in your filter function.
  • Adding classes as a string: The filter expects an array of classes, so add classes by appending to the array, not as a string.
  • Forgetting to hook the filter: Make sure to add add_filter( 'body_class', 'your_function' );.
  • Cache issues: Changes might not appear immediately if caching plugins or server caches are active.
  • Theme compatibility: Some themes may override body_class() or not call it properly; verify your theme outputs it in the <body> tag.

Works On

Server/Environment Compatibility
Apache Fully compatible
Nginx Fully compatible
LiteSpeed Fully compatible
…
WordPress Snippets

Adding Classes To previous_posts_link() And next_posts_link() In WordPress

Posted on August 19, 2025 By Admin No Comments on Adding Classes To previous_posts_link() And next_posts_link() In WordPress

Adding Classes To previous_posts_link() And next_posts_link() In WordPress

By default, WordPress’s previous_posts_link() and next_posts_link() functions generate simple anchor tags without any CSS classes. This limits your ability to style these pagination links easily. The quick fix is to add custom classes to these links, enabling better control over their appearance and behavior.

Quick Fix

  1. Use the updated versions of previous_posts_link() and next_posts_link() that accept an additional argument for classes.
  2. Add a filter in your functions.php or a small plugin to inject classes into the generated markup.
  3. Test the changes on your archive or blog pages to confirm the classes are applied.

Why This Happens

WordPress’s core functions previous_posts_link() and next_posts_link() were originally designed to output simple pagination links without class attributes. While modern WordPress versions allow some customization, these functions do not natively accept a class parameter. As a result, developers must use filters or custom wrappers to add classes for styling purposes.

When To Use

  • You want to style the “Previous” and “Next” pagination links differently from other links.
  • You are building a custom theme or child theme and need consistent markup.
  • You want to add JavaScript hooks or accessibility improvements via classes.

Updated Code For Modern WordPress

Since WordPress 5.9, the paginate_links() function and the_posts_pagination() support class arguments more directly, but previous_posts_link() and next_posts_link() do not. To add classes, you can use the get_previous_posts_link and get_next_posts_link filters to modify the output.

How To Add Classes via functions.php or a Small Plugin

Add the following code to your theme’s functions.php file or a custom plugin to add classes my-prev-class and my-next-class to the respective links:

/ Add custom class to previous_posts_link
function add_class_to_previous_posts_link( $link ) {
    if ( strpos( $link, 'class=' ) === false ) {
        $link = str_replace( '<a ', '<a class="my-prev-class" ', $link );
    } else {
        $link = str_replace( 'class="', 'class="my-prev-class ', $link );
    }
    return $link;
}
add_filter( 'previous_posts_link', 'add_class_to_previous_posts_link' );

/ Add custom class to next_posts_link
function add_class_to_next_posts_link( $link ) {
    if ( strpos( $link, 'class=' ) === false ) {
        $link = str_replace( '<a ', '<a class="my-next-class" ', $link );
    } else {
        $link = str_replace( 'class="', 'class="my-next-class ', $link );
    }
    return $link;
}
add_filter( 'next_posts_link', 'add_class_to_next_posts_link' );

Step-by-step Test

  1. Open your theme’s functions.php file or create a new plugin file.
  2. Copy and paste the code above into the file.
  3. Save and upload the file to your WordPress installation.
  4. Navigate to a paginated archive page (e.g., blog posts page).
  5. Inspect the “Previous” and “Next” pagination links in your browser’s developer tools.
  6. Confirm the links have the classes my-prev-class and my-next-class respectively.
  7. Apply CSS styles targeting these classes to customize the appearance.

Block Themes & Gutenberg Notes

With the rise of block themes and Gutenberg, pagination is often handled by blocks like the “Query Pagination” block. These blocks provide UI options to add classes directly in the editor. However, if you are using classic PHP templates or custom blocks that rely on previous_posts_link() and next_posts_link(), the above method remains valid.

For block themes, consider using the block editor’s built-in className controls or creating block variations with custom classes. For PHP-based themes, the filter method is the most straightforward approach.

Common Pitfalls

  • Classes not appearing: Ensure you are editing the correct functions.php file and that no other plugin or theme overrides the pagination output.
  • Multiple classes conflict: If the link already has classes, the code appends your class rather than replacing it to avoid conflicts.
  • Cache issues: Clear any caching plugins or server cache after making changes.
  • Incorrect HTML escaping: Use the filters exactly as shown to avoid breaking HTML output.

FAQ

Question Answer
Can I add multiple classes to the links? Yes. Modify the class string in the str_replace calls to include multiple classes separated by spaces, e.g., class="my-prev-class another-class".
Will this work with custom pagination plugins? Only if those plugins use previous_posts_link() and next_posts_link(). Otherwise, you need to check the plugin’s documentation for adding classes.
Can I add classes directly in the template files? No. The core functions do not accept a class parameter. You must use filters or custom markup to add classes.
Does this method affect SEO or accessibility? No. Adding classes does not affect SEO or accessibility negatively. You can even improve accessibility by adding ARIA attributes alongside classes.
Is this compatible with all WordPress versions? This method works on WordPress 4.7 and later, as the filters previous_posts_link and next_posts_link have been available since then.

Works on

  • Apache, Nginx
…
WordPress Snippets

Showing Random Posts In WordPress

Posted on August 19, 2025 By Admin No Comments on Showing Random Posts In WordPress

Showing Random Posts in WordPress

Displaying random posts in WordPress is a popular way to increase user engagement by showcasing diverse content each time a visitor lands on your site. Whether you want to highlight different blog posts, products, or portfolio items, showing random posts keeps your site dynamic and encourages visitors to explore more.

Quick Fix: Show Random Posts in WordPress

  1. Use the WP_Query class with 'orderby' => 'rand' to fetch random posts.
  2. Add the code snippet to your theme’s functions.php or create a small plugin.
  3. Call the function in your template files or use a shortcode to display random posts anywhere.

Why This Happens

WordPress does not provide a built-in widget or block to show random posts by default. You need to customize the query to order posts randomly. Using 'orderby' => 'rand' in WP_Query instructs WordPress to shuffle the posts before returning them. This approach is simple and effective but requires adding custom PHP code or using a plugin.

When to Use Showing Random Posts

  • Increase page views: Encourage visitors to browse more content.
  • Highlight older posts: Give visibility to posts that might otherwise be overlooked.
  • Enhance user experience: Make your site feel fresh and dynamic on each visit.
  • Promote diverse content: Showcase different categories or post types randomly.

Updated Code for Modern WordPress

Here is a clean, modern, and reusable function to fetch and display random posts. It uses WP_Query with proper escaping and supports customization of post type and number of posts.

function show_random_posts( $args = array() ) {
    $defaults = array(
        'post_type'      => 'post',
        'posts_per_page' => 5,
        'orderby'        => 'rand',
        'post_status'    => 'publish',
    );

    $query_args = wp_parse_args( $args, $defaults );

    $random_query = new WP_Query( $query_args );

    if ( $random_query->have_posts() ) {
        echo '<ul class="random-posts-list">';
        while ( $random_query->have_posts() ) {
            $random_query->the_post();
            echo '<li><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></li>';
        }
        echo '</ul>';
        wp_reset_postdata();
    } else {
        echo '<p>No posts found.</p>';
    }
}

How to Add This via functions.php or a Small Plugin

Option 1: Add to functions.php

  1. Open your active theme folder.
  2. Locate and edit the functions.php file.
  3. Paste the show_random_posts() function code at the end.
  4. Call show_random_posts(); in any template file where you want to display random posts.

Option 2: Create a Small Plugin

  1. Create a new folder named random-posts-display in wp-content/plugins.
  2. Create a file random-posts-display.php inside that folder.
  3. Paste the following code:
<?php
/**
 * Plugin Name: Random Posts Display
 * Description: Display random posts anywhere using a shortcode.
 * Version: 1.0
 * Author: Your Name
 */

function rpd_show_random_posts( $atts ) {
    $atts = shortcode_atts( array(
        'post_type'      => 'post',
        'posts_per_page' => 5,
    ), $atts, 'random_posts' );

    $query_args = array(
        'post_type'      => sanitize_text_field( $atts['post_type'] ),
        'posts_per_page' => intval( $atts['posts_per_page'] ),
        'orderby'        => 'rand',
        'post_status'    => 'publish',
    );

    $random_query = new WP_Query( $query_args );

    if ( $random_query->have_posts() ) {
        $output = '<ul class="random-posts-list">';
        while ( $random_query->have_posts() ) {
            $random_query->the_post();
            $output .= '<li><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></li>';
        }
        $output .= '</ul>';
        wp_reset_postdata();
    } else {
        $output = '<p>No posts found.</p>';
    }

    return $output;
}
add_shortcode( 'random_posts', 'rpd_show_random_posts' );
  1. Activate the plugin via the WordPress admin dashboard.
  2. Use the shortcode [random_posts] in posts, pages, or widgets to display random posts.

Step-by-Step Test

  1. Add the function or plugin code as described above.
  2. Insert <?php show_random_posts(); ?> in a theme template file (e.g., sidebar.php or footer.php).
  3. Or add the shortcode [random_posts] in the WordPress editor.
  4. Visit your site’s front end and refresh the page multiple times.
  5. Verify that different posts appear randomly each time.

Block Themes & Gutenberg Notes

For block themes or full site editing (FSE), you cannot directly insert PHP code in blocks. Instead, use the shortcode method via a Shortcode block or create a custom block plugin that wraps this functionality.

  • Insert a Shortcode block and add [random_posts].
  • For advanced users, create a dynamic block that calls show_random_posts() on render.
  • Remember that caching plugins or server-side caching might prevent the randomization from updating on
…
WordPress Snippets

Adding Classes to the Current Page Item in wp_nav_menu()

Posted on August 19, 2025 By Admin No Comments on Adding Classes to the Current Page Item in wp_nav_menu()

Adding Classes to the Current Page Item in wp_nav_menu()

If you want to add a custom class to the current menu item in WordPress navigation, you’ve come to the right place. By default, WordPress adds classes like current-menu-item to highlight the active page in menus, but sometimes you need to add your own classes for styling or JavaScript targeting. This tutorial shows you how to add class to current menu item WordPress easily and cleanly.

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

  1. Hook into the nav_menu_css_class filter.
  2. Check if the menu item is the current page.
  3. Add your custom class to the array of classes.
  4. Return the modified classes array.

This approach works perfectly in modern WordPress and can be added to your functions.php or a small custom plugin.

Why You Should Add a Custom Class to the Current Menu Item

  • Custom Styling: Sometimes the default current-menu-item class isn’t enough for your CSS needs.
  • JavaScript Targeting: Adding a unique class makes it easier to target the current menu item with scripts.
  • Theme Compatibility: Some themes or page builders require specific classes for active states.
  • Better Control: You can add multiple classes or change the class name to fit your project.

When to Use This Method

  • You want to add a class beyond the default WordPress classes.
  • You are building a custom theme or child theme and need precise control over menu item classes.
  • You want to add JavaScript hooks or CSS animations to the current menu item.
  • You are not using block-based navigation or want a PHP-based solution.

Updated Code for Modern WordPress

The best way to add a class to the current menu item is by using the nav_menu_css_class filter. Here’s a clean, modern example:

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

This code checks if the menu item already has the current-menu-item class and appends your custom class my-custom-current-class.

How to Add This via functions.php or a Small Plugin

To add this code, you can either place it in your theme’s functions.php file or create a small plugin.

Option 1: Add to functions.php

  1. Open your active theme folder.
  2. Locate and open functions.php.
  3. Paste the following code at the end:
function add_custom_class_to_current_menu_item($classes, $item) {
    if (in_array('current-menu-item', $classes, true)) {
        $classes[] = 'my-custom-current-class';
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_class_to_current_menu_item', 10, 2);
  1. Save the file and refresh your site to see the changes.

Option 2: Create a Small Plugin

  1. Create a new folder inside wp-content/plugins called custom-current-menu-class.
  2. Create a file named custom-current-menu-class.php inside this folder.
  3. Paste this code into the file:
<?php
/*
Plugin Name: Custom Current Menu Class
Description: Adds a custom 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, true)) {
        $classes[] = 'my-custom-current-class';
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_class_to_current_menu_item', 10, 2);
  1. Go to WordPress admin > Plugins and activate “Custom Current Menu Class.”
  2. Check your menu on the front end.

Step-by-Step Test

  1. Apply the code via functions.php or plugin as shown above.
  2. Go to Appearance > Menus and ensure your menu is assigned to a theme location.
  3. Visit your site’s front end and navigate to a page included in the menu.
  4. Inspect the menu item using browser developer tools.
  5. Look for the default current-menu-item class plus your custom class my-custom-current-class.
  6. Test your CSS or JavaScript targeting the new class.

Block Themes & Gutenberg Notes

With the rise of block themes and Gutenberg’s Navigation block, the way menus are rendered can differ:

  • Block Themes: The Navigation block outputs menus dynamically and may not use wp_nav_menu() filters.
  • Gutenberg Navigation Block: Custom classes for current items are handled internally or via block settings.
  • Workaround: For block themes, consider using wp_nav_menu_items filter or custom block styles.
  • Classic Themes: The method described here works perfectly for PHP-rendered menus.

Common Pitfalls

  • Class Not Appearing: Ensure your menu is properly assigned and the page is part of the menu.
  • Wrong Hook: Use nav_menu_css_class, not wp_nav_menu_items for adding classes to individual items.
  • Block Themes: This method may not work if your theme uses block-based navigation.
  • Cache Issues: Clear any caching plugins or server cache to see changes immediately.
  • Class Name Conflicts:
…
WordPress 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