My goal is to get the current WooCommerce sorting option selected, such as websitename.com/?orderby=popularity
and set whatever the current query selection is as a body class. (Ideally something like body
).
In the example below I am using if/elseif statements. I attempted this with a switch operator as well as simply using global $orderby
. I haven't been able to find any example covering this question and feeling quite stuck so I appreciate any help.
Thank you. Here is my current documentation:
add_filter( 'body_class', 'gaz_wc_sorting_as_body_class' );
function gaz_wc_sorting_as_body_class( $class ){
$orderby_value = $_GET['orderby'];
if ($orderby_value === 'popularity') {
array( ' popular ' => $class);
} elseif ($orderby_value === 'date') {
array( ' recent ' => $class);
} elseif ($orderby_value === 'price') {
array( ' cost-lo-hi ' => $class);
} elseif ($orderby_value === 'price-desc') {
array( ' cost-hi-lo ' => $class);
} else {
array( 'sort-clear ' => $class);
}
return $class;
}
CodePudding user response:
This might do the trick.
add_filter( 'body_class', 'gaz_wc_sorting_as_body_class' );
function gaz_wc_sorting_as_body_class( $class ){
$class = array('orderby' => '', 'order' => '');
if (self::isActive()) {
$query = new WC_Query();
$class = $query->get_catalog_ordering_args();
}
return $class;
}
CodePudding user response:
You can push your class name to the $class
array. You can use the array_push
function. try the below code.
function gaz_wc_sorting_as_body_class( $class ){
$orderby_value = $_GET['orderby'];
if ( $orderby_value === 'popularity' ) {
array_push( $class, 'popular' );
} elseif ( $orderby_value === 'date' ) {
array_push($class, 'recent');
} elseif ( $orderby_value === 'price' ) {
array_push($class, 'cost-lo-hi');
} elseif ( $orderby_value === 'price-desc' ) {
array_push($class, 'cost-hi-lo');
} else {
array_push($class, 'sort-clear');
}
return $class;
}
add_filter( 'body_class', 'gaz_wc_sorting_as_body_class' );