Using WordPress ‘page_css_class’ PHP filter

The page_css_class WordPress PHP filter allows you to modify the list of CSS classes applied to each page item in a list.

Usage

add_filter('page_css_class', 'your_custom_function', 10, 5);

function your_custom_function($css_class, $page, $depth, $args, $current_page_id) {
    // your custom code here
    return $css_class;
}

Parameters

  • $css_class (string[]): An array of CSS classes to be applied to each list item.
  • $page (WP_Post): Page data object.
  • $depth (int): Depth of the page, used for padding.
  • $args (array): An array of arguments.
  • $current_page_id (int): ID of the current page.

More information

See WordPress Developer Resources: page_css_class

Examples

Add a custom CSS class to all page items

This example adds a custom CSS class “my-custom-class” to all page items.

add_filter('page_css_class', 'add_custom_class_to_page_items', 10, 5);

function add_custom_class_to_page_items($css_class, $page, $depth, $args, $current_page_id) {
    $css_class[] = 'my-custom-class';
    return $css_class;
}

Add a depth-based CSS class

This example adds a depth-based CSS class to each page item (e.g., “depth-1”, “depth-2”).

add_filter('page_css_class', 'add_depth_based_class', 10, 5);

function add_depth_based_class($css_class, $page, $depth, $args, $current_page_id) {
    $css_class[] = 'depth-' . ($depth + 1);
    return $css_class;
}

Highlight the current page

This example adds the “current-page” CSS class to the current page item.

add_filter('page_css_class', 'highlight_current_page', 10, 5);

function highlight_current_page($css_class, $page, $depth, $args, $current_page_id) {
    if ($page->ID == $current_page_id) {
        $css_class[] = 'current-page';
    }
    return $css_class;
}

Remove all default CSS classes

This example removes all default CSS classes from page items.

add_filter('page_css_class', 'remove_all_default_classes', 10, 5);

function remove_all_default_classes($css_class, $page, $depth, $args, $current_page_id) {
    return array();
}

Add a custom class to top-level pages only

This example adds the “top-level-page” CSS class to top-level pages (depth 0).

add_filter('page_css_class', 'add_custom_class_to_top_level_pages', 10, 5);

function add_custom_class_to_top_level_pages($css_class, $page, $depth, $args, $current_page_id) {
    if ($depth == 0) {
        $css_class[] = 'top-level-page';
    }
    return $css_class;
}