How to add the Advanced Headers ID to body classes

computer code on screen

I recently ran across a situation where I was using Astra Pro’s Page Headers feature and needed to add CSS styles to one particular header layout. There is a .ast-advanced-headers body class, but nothing that would allow targeting one header layout while ignoring another (as of v3.2.0). Fortunately, we can add some custom code that adds the specific header layout ID to body classes using the Wordpress body_class hook.

/** 
 * Check for Astra Advanced Headers and add header ID class to body classes for per-header styling
 * @author Tristan Mason <tristanmason.com>
 */
function tmac_add_advanced_header_class( $classes ) {
    // only run if Advanced Headers exists and is enabled on this page
    if ( (int)method_exists('Astra_Ext_Advanced_Headers_Data', 'get_current_page_header_ids') && in_array('ast-advanced-headers',$classes) ) {
        $tmac_header_ids = Astra_Ext_Advanced_Headers_Data::get_current_page_header_ids();
        $classes[] = 'tmac-header-id-' . $tmac_header_ids;
    }

    return $classes;
}
add_action( 'body_class', 'tmac_add_advanced_header_class', 15 );