'no'); }); add_filter('usedkit_save_settings', function ($out, $post) { return $out + array('similar' => !empty($post['similar']) ? 'yes' : 'no'); }, 10, 2); add_action('usedkit_settings_rows', function ($s) { ?> get_id(); $ids = get_transient($cache); if (is_array($ids)) { return $ids; } $cats = $product->get_category_ids(); $args = array('limit' => 60, 'status' => 'publish', 'stock_status' => 'instock', 'exclude' => array($product->get_id()), 'visibility' => 'catalog', 'orderby' => 'date', 'order' => 'DESC'); if ($cats) { $args['category'] = array_map(function ($id) { $t = get_term($id, 'product_cat'); return $t ? $t->slug : ''; }, $cats); } $candidates = wc_get_products($args); $keys = function_exists('usedkit_model_keys') ? usedkit_model_keys(array_merge(array($product), $candidates), false) : array(); $key = $keys[$product->get_id()] ?? ''; $price = function_exists('usedkit_sold_price') ? usedkit_sold_price($product) : (float) $product->get_price(); usort($candidates, function ($a, $b) use ($keys, $key, $price) { $sa = $key !== '' && ($keys[$a->get_id()] ?? '') === $key; $sb = $key !== '' && ($keys[$b->get_id()] ?? '') === $key; if ($sa !== $sb) { return $sb <=> $sa; } return abs((float) $a->get_price() - $price) <=> abs((float) $b->get_price() - $price); }); $ids = array_map(function ($p) { return $p->get_id(); }, array_slice($candidates, 0, $n)); set_transient($cache, $ids, HOUR_IN_SECONDS); return $ids; } add_action('woocommerce_after_single_product_summary', function () { global $product; if (!$product || $product->is_in_stock() || usedkit_settings()['similar'] !== 'yes') { return; } $ids = usedkit_similar_ids($product); if (!$ids) { return; } // Through WooCommerce's own related-products template, so every theme lays it out and // styles it like its related products; only the heading is ours. $heading = function () { return __('In stock now', 'usedkit'); }; add_filter('woocommerce_product_related_products_heading', $heading, 99); wc_get_template('single-product/related.php', array( 'related_products' => array_filter(array_map('wc_get_product', $ids)), 'columns' => 4, 'posts_per_page' => 4, 'orderby' => 'none')); remove_filter('woocommerce_product_related_products_heading', $heading, 99); // These are this page's related products now: WooCommerce's own, however the theme // shows them, would repeat them. add_filter('woocommerce_related_products', '__return_empty_array', 99); }, 18);