12/13/2016 - 3:53 PM

Adding custom classes to markup

Adding custom classes to markup

//* Do NOT include the opening php tag shown above. Copy the code shown below.

 * Examples to add custom classes to Genesis WordPress Framework Markup when using HTML5 output
add_action( 'genesis_setup', 'srf_add_cust_classes', 15 ); // Priority 15 ensures it runs after Genesis itself has setup.
function srf_add_cust_classes() {
    add_filter( 'genesis_attr_site-inner', 'srf_attr_site_inner' );
    add_filter( 'genesis_attr_content-sidebar-wrap', 'srf_attr_content_sidebar_wrap' );
    add_filter( 'genesis_attr_content', 'srf_attr_content' );
    add_filter( 'genesis_attr_sidebar-primary', 'srf_attr_sidebar_primary' );
} // Don't add a closing marker comment here - it just clutters the code

// Don't nest functions, move them outside of the hooked in function. While nested functions work, if the outer function is called again for whatever reason, PHP will throw a wobbly when it tries to redefine an existing function.

// Just for fun, I've refactored the common code into one function, and improved it with sanitization.

function srf_add_class( $attr, $class ) {
    $attr['class'] .= ' ' . sanitize_html_class( $class );
    return $attr;

// Now the rest of the functions are one line each, and the name of the called function tells us what's happening (add a class).

function srf_attr_site_inner( $attr ) {
    return srf_add_class( $attr, 'example-class-1' );

function srf_attr_content_sidebar_wrap( $attr ) {
    return srf_add_class( $attr, 'example-class-2' );

function srf_attr_content( $attr ) {
    return srf_add_class( $attr, 'example-class-3' );

function srf_attr_sidebar_primary( $attr ) {
    return srf_add_class( $attr, 'example-class-4' );