• Resolved curiousforge

    (@curiousforge)


    Hello!

    I’m trying to sort my products by the date the sale starts. I’d like products with the nearest sale date at the top, followed by products with approaching sale dates, in descending order. I’ve tried the following approaches, but neither has worked. In both cases, no products appear in the catalog. All of my products are variable, which could be part of the issue.

    Below is a simple approach trying to filter by the sale date,

    add_filter( 'woocommerce_get_catalog_ordering_args', 'sort_products_by_variation_sale_date' );
    
    function sort_products_by_variation_sale_date( $args ) {
        $args['meta_key'] = '_sale_price_dates_from';
        $args['orderby'] = 'meta_value';
        return $args;
    }
    

    I also tried creating a custom meta field, populating it with the top variable product sale date, then filtering by the custom meta field, however that too didn’t work.

    //Create Custom Field
    
    add_post_meta( $parent_id, 'latest_variation_sale_date', '', true );
    
    //Update Custom Meta Field
    
    add_action( 'save_post', 'update_parent_sale_date', 10, 3 );
    
    function update_parent_sale_date( $post_id, $post, $update ) {
      if ( 'product_variation' !== $post->post_type ) {
        return;
      }
    
      $parent_id = wp_get_post_parent_id( $post_id );
      $sale_price_dates_from = get_post_meta( $post_id, '_sale_price_dates_from', true );
      $sale_price_dates_to = get_post_meta( $post_id, '_sale_price_dates_to', true );
      if ( ! empty( $sale_price_dates_from ) && ! empty( $sale_price_dates_to ) ) {
        update_post_meta( $parent_id, 'latest_variation_sale_date', $sale_price_dates_from );
      }
    }
    
    //Sort by Custom Meta Field
    
    add_filter( 'woocommerce_get_catalog_ordering_args', 'sort_products_by_variation_sale_date' );
    
    function sort_products_by_variation_sale_date( $args ) {
        $args['meta_key'] = 'latest_variation_sale_date';
        $args['orderby'] = 'meta_value';
        $args['order'] = 'DESC';
        return $args;
    }
    

    Any tips would be greatly appreciated. I’m fairly new to PHP. Many thanks.

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Sort Products by Sale Date’ is closed to new replies.