Site logo

[Resolved] generate_page_class for parent page + all child pages

Home Forums Support [Resolved] generate_page_class for parent page + all child pages

Home Forums Support generate_page_class for parent page + all child pages

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #2594443
    Tina

    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.

    #2594451
    David
    Staff
    Customer Support

    Hi there,

    can i see the page you’re trying to apply this to ?

    #2594506
    Tina

    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!

    #2594520
    Tina

    (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)

    #2594637
    David
    Staff
    Customer Support

    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!!

Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.