79439155

Date: 2025-02-14 11:11:57
Score: 0.5
Natty:
Report link

from: https://wordpress.org/support/topic/moving-sold-items-to-bottom-of-page-automatically/

class iWC_Orderby_Stock_Status {
    public function __construct() {
        if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
            add_filter('posts_clauses', array($this, 'order_by_stock_status'), 2000);
        }
    }

    public function order_by_stock_status($args) {
        global $wpdb;

        if (is_woocommerce() && (is_shop() || is_product_category() || is_product_tag())) {
            // Include posts with '_stock_status' meta key in the SQL query
            $args['join'] .= " LEFT JOIN {$wpdb->postmeta} istockstatus ON {$wpdb->posts}.ID = istockstatus.post_id AND istockstatus.meta_key = '_stock_status'";

            // Order by '_stock_status' in ascending order ('instock' comes before 'outofstock')
            $args['orderby'] = "istockstatus.meta_value ASC, " . $args['orderby'];
        }

        return $args;
    }
}

new iWC_Orderby_Stock_Status;
Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: glocsw