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 class="popularity"
).
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;
}
3
Answers
Solution - Woo hoo! Bhautik is correct about
array_push($class, 'string');
Though it wasn't working for me until I changed the singular quotations around the string to push into double quotations. Using double quotations, this documentation using array_push() works like a charm!Though, I took it one step further to make the function dynamic for orderby queries by pushing the $orderby_value as the class name pushed to the body class array.
For anyone interested in using static classes pushed to the body HTML element, here is my documentation that worked with Bhautik's solution:
This might do the trick.
You can push your class name to the
$class
array. You can use thearray_push
function. try the below code.