Reputation: 25
Woocommerce cross-sells are displayed on cart page. By default they are sorted randomly. Can anyone please help me to sort them by date (= publishing date of product)? Thanks very much!
Here is the content of cross-sells.php :
<?php
/**
* Cross-sells
*
* This template can be overridden by copying it to yourtheme/woocommerce/cart/cross-sells.php.
*
* @see https://docs.woocommerce.com/document/template-structure/
* @author WooThemes
* @package WooCommerce/Templates
* @version 3.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( $cross_sells ) : ?>
<div class="cross-sells">
<h2><?php _e( 'You may be interested in…', 'woocommerce' ) ?></h2>
<?php woocommerce_product_loop_start(); ?>
<?php foreach ( $cross_sells as $cross_sell ) : ?>
<?php
$post_object = get_post( $cross_sell->get_id() );
setup_postdata( $GLOBALS['post'] =& $post_object );
wc_get_template_part( 'content', 'product' ); ?>
<?php endforeach; ?>
<?php woocommerce_product_loop_end(); ?>
</div>
<?php endif;
wp_reset_postdata();
HERE is the SOLUTION:
You do NOT have to edit cross-sells.php ! Instead you can create a little plugin that does the job:
Thanks to LoicTheAztec for providing the filter-hook for this solution! (By creating a plugin for this filter-hook you do not have to edit function.php or create a child theme.)
Here is the code for this little plugin:
<?php
/**
* Plugin Name: Woocommerce Sort Cross-sales by Date
* Description: This plugin is used to sort cross-sells by date
* Author: ARaction GmbH with help of LoicTheAztec - no guarantee or support!
* Version: 0.1
*/
/* Your code goes below here. */
add_filter( 'woocommerce_cross_sells_orderby', 'custom_cross_sells_orderby', 10, 1 );
function custom_cross_sells_orderby( $orderby ){
$orderby = 'date';
return $orderby;
}
/* Your code goes above here. */
?>
Upvotes: 1
Views: 758
Reputation: 254492
To order cross sells by date you can use this filter hook:
add_filter( 'woocommerce_cross_sells_orderby', 'custom_cross_sells_orderby', 10, 1 );
function custom_cross_sells_orderby( $orderby ){
$orderby = 'date';
return $orderby;
}
Code goes in function.php file of your active child theme (active theme or in any plugin file).
Tested and works.
Upvotes: 1