Reputation: 2792
In WooCommerce, I am trying to output a list of related products on an individual product page. I am able to retrieve an array of related products as follows:
<?
// Current product ID
$currentProductId = $product->get_id();
// Related products
$relatedProducts = wc_get_related_products($currentProductId);
print_r($relatedIssues);
?>
However, this outputs the array as follows, which appears to be a random order.
Array ( [0] => 28 [1] => 27 [2] => 30 [3] => 26 )
I would like to arrange this array by numerical value, from high to low, if possible?
Thanks.
Upvotes: 0
Views: 384
Reputation: 375
There are many ways to achieve this:
rsort()
rsort($relatedProducts, SORT_NUMERIC);
Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys. This is irrelevant in this case but would wreck havoc when array keys are important for further processing.
usort()
usort($relatedProducts, sort_desc);
function sort_desc( $a, $b) {
if ( $a === $b ) {
return 0;
}
return ( $a > $b ) ? -1 : 1;
}
wc_products_array_orderby( $relatedProducts, $orderby = 'id', $order = 'desc' )
You can not only sort by Product ID but also by title, date, modified (date), menu_order, price
.
This eventually calls following function for sorting based on ID, but will do array_reverse()
for 'desc' order on final output:
/**
* Sort by id.
* @since 3.0.0
* @param WC_Product object $a
* @param WC_Product object $b
* @return int
*/
function wc_products_array_orderby_id( $a, $b ) {
if ( $a->get_id() === $b->get_id() ) {
return 0;
}
return ( $a->get_id() < $b->get_id() ) ? -1 : 1;
}
Related products are already hooked in
woocommerce_after_single_product_summary
action in
content-single-product.php
template with
woocommerce_output_related_products
function.
To modify the order of related products on Single Product page you
can simply filter with woocommerce_output_related_products_args
. Or
when you need it outside the template such as in sidebars, you can use [related_products orderby="ID"]
shortcode.
To change the layout I would strongly recommend to use and customize
WooCommerce template related.php
from template\single-product
folder instead of adding additional code to content-single-product.php
.
Breaking away from standard WooCommerce/WordPress conventions may create code cruft which would be harder to maintain, debug or upgrade in future. Further to that other plugins, theme or your own custom code which may want to 'hook' in to the said function OR it's HTML output, won't be able to do so.
Upvotes: 3
Reputation: 3697
Just try this:
usort($relatedIssues, function($a, $b) { return ($a > $b) ? -1 : 1; });
Upvotes: 2