Created
July 11, 2021 17:45
-
-
Save jorpdesigns/1ffbb96813c08228c7be594297312f69 to your computer and use it in GitHub Desktop.
Function to sort an array of WooCommerce product ids based on custom value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // This function sorts the product based on menu order. You can get other numerical conditions here: https://www.businessbloomer.com/woocommerce-easily-get-product-info-title-sku-desc-product-object/#more-72711 | |
| function product_multiarray_sort( $productIDsArray ) { | |
| $productMultiArray = array(); | |
| $sortedProductIDsArray = array(); | |
| foreach ( $productIDsArray as $productID ) { | |
| $product = wc_get_product( $productID ); | |
| $menuOrder = $product->get_menu_order(); // Replace with preferred custom value e.g. $price = $product->get_price() | |
| $productMultiArray[] = array('id' => $productID, 'order' => $menuOrder); // Replace second column with preferred custom value e.g. 'price' => $price | |
| } | |
| $menuOrderColumn = array_column($productMultiArray, 'order'); // Replace with preferred custom value e.g. $priceColumn = array_column($productMultiArray, 'price') | |
| array_multisort($menuOrderColumn, SORT_ASC, $productMultiArray); // Replace with preferred custom value e.g. array_multisort($priceColumn, SORT_ASC, $productMultiArray). You can also replace SORT_ASC with SORT_DESC to sort in descending order | |
| // Get ids of sorted multiarray | |
| foreach($productMultiArray as $productArray) { | |
| $sortedProductIDsArray[] = $productArray['id']; | |
| } | |
| return $sortedProductIDsArray; | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment