WooCommerce Sale Items pushed to beginning
Hey Everybody!
I promised I’d get a blog post out today, so here goes! Recently, I had a client project that required all sale items be pushed to the beginning of the products page. With a little bit of creative coding, and manipulating a few queries, I got it to work. Here we go:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
/** * Sale Products Up Front */ add_action( 'woocommerce_product_query', 'cur_sale_products_up_front', 10, 2); add_filter('posts_request', 'cur_modify_products_query', 10, 2); add_filter('loop_start', 'cur_reorder_sale_items'); function cur_replace_text($startPoint, $endPoint, $newText, $source) { $regex = '#('.preg_quote($startPoint).')(.*)('.preg_quote($endPoint).')#si'; preg_match( $regex, $source, $matches); $newText = $newText . $matches[2]; return preg_replace($regex, '$1'.$newText.'$3', $source); } function cur_sale_products_up_front($q, $this) { if ( isset($_SESSION['orderby']) && $_SESSION['orderby'] == 'menu_order' ) : $q->set('meta_key', '_sale_price'); $q->set('products_query', 'true'); endif; return $q; } function cur_modify_products_query($request, $object){ if ( ! empty( $object->query_vars['products_query'] ) && isset($_SESSION['orderby']) && $_SESSION['orderby'] == 'menu_order' ) : global $wpdb; $new_orderby = $wpdb->postmeta . '.meta_value+0 desc, '; $request = cur_replace_text('ORDER BY ', ' LIMIT', $new_orderby, $request); endif; return $request; } function cur_reorder_sale_items($query){ if( ! empty( $query->posts ) && $query->query_vars['post_type'] == 'product' ) : $posts = &$query->posts; foreach( $posts as $key => $post ) : $sale_price = get_post_meta($post->ID,'_sale_price', TRUE); if( !empty( $sale_price ) ) $sale_products[$key] = $sale_price; endforeach; if( !empty ($sale_products ) ) : arsort( $sale_products); foreach( $sale_products as $key => $post ) : $sale_products[$key] = $posts[$key]; unset( $posts[$key] ); array_unshift( $posts, $sale_products[$key] ); endforeach; endif; endif; return $query; } |

2 Comments
Cristaim
March 6, 2013exactly the same but I need to show the items in another blog within the same network Multisite, I get this with switch_to_blog (), but since I can print out your functions?
u571
March 6, 2013Hey Cristaim! Are you trying to show sale products from one site on a network on another site on the same network?