Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

Add class to header or body when header element is active

  • TwoLoonSoftware

    I have a header element that is applied to a subset of pages, and I need to apply some styling to the header. I’d like to add a class to the merged header (or better, the body element when the header is active).
    Is there a way to do this?

  • Hi there,

    The merged header has a default class header-wrap.

    If you want to target the body, you can do body:has(.header-wrap), if you want to target the header, try .header-wrap .site-header.

  • TwoLoonSoftware

    Can I have different classes for different headers?

  • Hi there,

    You can use this snippet:

    function my_header_element_body_class($classes)
    {
    	// ID of your Header Element
    	$header_element_id = 123; // Replace with your actual Header Element ID
    
    	// Get the element's display conditions
    	$display_conditions = get_post_meta($header_element_id, '_generate_element_display_conditions', true) ?: array();
    	$exclude_conditions = get_post_meta($header_element_id, '_generate_element_exclude_conditions', true) ?: array();
    	$user_conditions = get_post_meta($header_element_id, '_generate_element_user_conditions', true) ?: array();
    
    	// Check if the Header Element would display on the current page
    	if (class_exists('GeneratePress_Conditions')) {
    		$element_displays = GeneratePress_Conditions::show_data(
    			$display_conditions,
    			$exclude_conditions,
    			$user_conditions
    		);
    
    		// If the element would display, add our custom class
    		if ($element_displays) {
    			$classes[] = 'has-header-element';
    		}
    	}
    
    	return $classes;
    }
    add_filter('body_class', 'my_header_element_body_class');

    Simply replace 123 with the header element ID. The snippet will add the has-header-element class to the <body> tag on pages where this element is applied.

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