Question

I'm looking to add some custom classes to the body element based on theme options.

I've setup two theme options ('rounded_corner_radio' & 'gradient_radio') that successfully output their values to the front-end using echo so I know they're working.

What I now need to do is insert those values into the body class but can't work out how. Here's what I currently have, any suggestions are very welcome.

<?php 
  $rounded_corner_radio = of_get_option( 'rounded_corner_radio' ); 
  $gradient_radio = of_get_option( 'gradient_radio' );
  function custom_body_classes( $classes ) {
    $classes[] = $rounded_corner_radio;
    $classes[] = $gradient_radio;
    return $classes;
  }
  add_filter( 'body_class','custom_body_classes' );
?>
<body <?php  body_class( ''); ?>>

Thanks in advance,

Tom

Was it helpful?

Solution

Review how the variable scope works..

Let's not add yet another global variable, instead we can e.g. fetch the option values within the filter's callback:

function wpse251261_custom_body_classes( $classes ) {

     // Get option values
     $rounded_corner_radio = of_get_option( 'rounded_corner_radio' ); 
     $gradient_radio       = of_get_option( 'gradient_radio' );

     // Assign new body classes
     $classes[] = esc_attr( $rounded_corner_radio );
     $classes[] = esc_attr( $gradient_radio );

     return $classes;
}

add_filter( 'body_class','wpse251261_custom_body_classes' );

Note that we escaped it with esc_attr(), because the body_class filter is applied after such escaping in get_body_class().

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top