Archived topic
generate_page_class for parent page + all child pages
4 replies · Started by Tina on April 3, 2023
Hi,
I'm trying to use this filter to add a page class, but only on a parent page and its child pages. It's not working, however, is there something wrong with my code?
add_filter( 'generate_page_class', function( $classes ) {
global $post;
if ( is_page() && $post->post_parent == '34' ) {
$classes[] = 'class_name';
}
return $classes;
} );
Note that this is not working either (adding a page class only to home page), so perhaps I'm setting up the conditional wrong in the first place):
add_filter( 'generate_page_class', function( $classes ) {
if ( is_home() ) {
$classes[] = 'class_name';
}
return $classes;
} );
Any help greatly appreciated!
Thank you so much.
Hi there,
can i see the page you're trying to apply this to ?
Hi David,
working locally right now but I got it to work without the conditional:
function parent_page_class( $classes ) {
global $post;
$parent_slug = get_post_field( 'post_name', $post->post_parent );
$classes[] = $parent_slug;
return $classes;
}
add_filter( 'generate_page_class', 'parent_page_class' );
Still don't know why the first one wouldn't work but this is better imo..
Thanks for the quick response!
(for anybody reading: wordpress already has a parent page ID body class, so my solution is kind of redundant, I was hoping to somehow write a universal solution for a multilingual site but it's not working as expected. well. at least here's the code for anyone who finds it useful)
Yeah, thats a handy way to do it - or as you said you can filter it down from the body if needed.
Glad to see you got it working and thanks for sharing the solution!!