There are many ways to achieve this:
Option 1: Good old 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.
Option 2: usort()
usort($relatedProducts, sort_desc);
function sort_desc( $a, $b) {
if ( $a === $b ) {
return 0;
}
return ( $a > $b ) ? -1 : 1;
}
Option 3: wc_products_array_orderby()
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;
}
Why should you avoid coding custom related products layout directly on Single Product page template?
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.