Skip to content

Instantly share code, notes, and snippets.

@lucasstark
Last active August 25, 2021 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasstark/d0ccc791320ebce0f7604a96d8d6ba17 to your computer and use it in GitHub Desktop.
Save lucasstark/d0ccc791320ebce0f7604a96d8d6ba17 to your computer and use it in GitHub Desktop.
Organize swatches into groups based on the attribute name after a dash.
class Swatches_Organizer {
private static $instances = null;
public static function register( $taxonomy_slug ) {
if ( self::$instances == null ) {
self::$instances = new Swatches_Organizer( $taxonomy_slug );
}
}
protected $taxonomy_slug;
protected $current_group;
protected $groups = [];
protected function __construct( $taxonomy_slug ) {
$this->taxonomy_slug = $taxonomy_slug;
add_action( 'woocommerce_swatches_before_picker_items', [ $this, 'bind_hooks' ] );
}
function bind_hooks( $config ) {
if ( $config->_attribute_name == $this->taxonomy_slug ) {
add_action( 'woocommerce_swatches_before_picker_item', [
$this,
'on_woocommerce_swatches_before_picker_item'
] );
add_action( 'woocommerce_swatches_after_picker_item', [
$this,
'on_woocommerce_swatches_after_picker_item'
] );
add_action( 'woocommerce_swatches_after_picker_items', [
$this,
'on_woocommerce_swatches_after_picker_items'
] );
}
}
function unbind_hooks() {
remove_action( 'woocommerce_swatches_before_picker_item', [
$this,
'on_woocommerce_swatches_before_picker_item'
] );
remove_action( 'woocommerce_swatches_after_picker_item', [
$this,
'on_woocommerce_swatches_after_picker_item'
] );
remove_action( 'woocommerce_swatches_after_picker_items', [
$this,
'on_woocommerce_swatches_after_picker_items'
] );
}
function on_woocommerce_swatches_before_picker_item( $swatch_term ) {
$this->current_group = substr( $swatch_term->term_label, strpos( $swatch_term->term_label, '-' ) + 2 );
if ( !isset( $this->groups[ $this->current_group ] ) ) {
$this->groups[ $this->current_group ] = [];
}
ob_start();
}
function on_woocommerce_swatches_after_picker_item( $swatch_term ) {
$this->groups[ $this->current_group ][] = ob_get_clean();
}
function on_woocommerce_swatches_after_picker_items() {
foreach ( array_keys( $this->groups ) as $group ) {
echo '<div>';
echo '<h4>' . $group . '</h4>';
foreach ( $this->groups[ $group ] as $item ) {
echo $item;
}
echo '</div>';
}
$this->unbind_hooks();
}
}
// Register the organizer for the particular product attribute.
Swatches_Organizer::register( 'pa_color-swatches' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment