• Resolved melebius

    (@melebius)


    First of all, thanks for making this plugin that seems to be able to help me and my customers. Unfortunately, I am not able to make it always choose the variation I’d prefer.

    I selected sorting by Position and thought it means the Custom ordering of the attribute values (/wp-admin/edit.php?post_type=product&page=product_attributes). However, the default variation selected by the plugin seems to match the lowest variation ID (although I have selected Position).

    Can I make the plugin sort by custom order anyhow? And what does Sort by Position mean actually?

Viewing 1 replies (of 1 total)
  • Thread Starter melebius

    (@melebius)

    I looked into the code of the plugin and found that the position is simply the order in which WordPress returns the attribute term which simply matches the ID, at least in my case.

    However, I also found I can alter the position value (used for sorting) using the filter hpy_fdv_build_attribute_filter. I got the list of the attribute terms for my variation attribute (the attribute with checked “Used for variations”) and set the position accordingly:

    add_filter( 'hpy_fdv_build_attribute_filter', set_position_by_variation_attributes' );
    /**
     * Replaces the position attribute with the position in the attribute terms list.
     * 
     * Assuming just **one** variation attribute.
     * If multiple attributes needed to be taken into account,
     * you would have to define a custom criterion function
     * instead of just assigning $term_idx to position.
     */
    function set_position_by_variation_attributes( array $attributes ) {
      $var_attribs = wc_get_product_variation_attributes( $attributes[ 'id' ] );
      foreach ($var_attribs as $attr_name_full => $current_term) {
        $attr_name = substr( $attr_name_full, strlen( 'attribute_' ) ); // strip 'attribute_' prefix
    
        // Search for the current variation’s term ($current_term) among available terms.
        // Terms returned by get_terms() are sorted according to the Product Attributes back-end page.
        foreach ( get_terms( $attr_name ) as $term_idx => $term ) {
          if ( $term->slug == $current_term ) {
            $attributes[ 'position' ] = $term_idx;
            break;
          }
        }
      }
      return $attributes;
    }

    Thank you for making this plugin and making the mentioned filter (among others) available! Feel free to incorporate my code into the plugin if you find it useful.

Viewing 1 replies (of 1 total)
  • The topic ‘Sorting by position’ is closed to new replies.