I am trying to set my default sort for my products in WordPress with Woocommerce to show me all the featured products first, then any new products that are no older than 120 days, then show everything else by menu order and finally by the title. Below is my initial code that does kind of do what i want but i have no idea how to set a date range of 120 days or newer.
add_filter('woocommerce_get_catalog_ordering_args', 'am_woocommerce_catalog_orderby');
function am_woocommerce_catalog_orderby( $args ) {
if(!$_GET['orderby']) {
$args['orderby'] = array(
'meta_value' => 'DESC',
'date' => 'DESC',
'menu_order' => 'ASC',
'title' => 'ASC'
);
$args['meta_key'] = '_featured';
return $args;
}
}
UPDATE
Ok so I have done some searching and i found some code that is supposed to loop through arguments and then remove duplicates, being a noob I am not sure what I am missing. My code below gets an error: Fatal error: Call to a member function have_posts() on null
so i tried to add $loop = new WP_Query( $args );
but then the code does nothing. So I am lost and looking for some clues on what i need to fix. Thanks!
add_filter('woocommerce_get_catalog_ordering_args', 'am_woocommerce_catalog_orderby');
function am_woocommerce_catalog_orderby( $my_post_array ) {
if(!$_GET['orderby']) {
//First loop - show featured
$args['orderby'] = array( 'meta_value' => 'DESC' );
$args['meta_key'] = '_featured';
while ( $loop->have_posts() ) : $loop->the_post();
$post_id = get_the_ID();
$my_post = my_post_function($post_id);
//Store the items in an array
$my_post_array [] = $my_post;
query_posts($args);
endwhile;
//Second loop - Show newer than 6 months
$args = array(
'orderby' => 'date',
'order' => 'DESC',
'date_query' => array(
array(
'before' => '6 months ago',
),
)
);
while ( $loop->have_posts() ) : $loop->the_post();
$post_id = get_the_ID();
$my_post = my_post_function($post_id);
//Store the items in an array
$my_post_array [] = $my_post;
query_posts($args);
endwhile;
//Third loop - show everything else and sort by menu_order and title
$args['orderby'] = array( 'menu_order' => 'ASC', 'title' => 'ASC' );
while ( $loop->have_posts() ) : $loop->the_post();
$post_id = get_the_ID();
$my_post = my_post_function($post_id);
//Store the items in an array
$my_post_array [] = $my_post;
query_posts($args);
endwhile;
//Remove duplicate entries from the array
array_unique ( $my_post_array, SORT_STRING );
}
}
Update 2
I have yet to have any luck, any chance someone can take a look at my latest code above and give me some ideas on a direction to try? This loop does not seem to work for this filter when adding to the functions.php, maybe i need to do something different. Any help is appreciated!