Created
February 22, 2016 10:34
-
-
Save mikejolley/5511eb1fddace7606193 to your computer and use it in GitHub Desktop.
Simple Global Attribute Size Switcher for WooCommerce Variable Products
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Show the size switcher. | |
*/ | |
function size_switcher_display() { | |
global $product; | |
echo '<div class="wc-size-switcher">'; | |
echo __( 'Display sizes as:', 'woocommerce-size-switcher' ) . ' '; | |
echo '<a href="' . esc_url( add_query_arg( 'size_display', 'UK' ) ) . '">UK</a> '; | |
echo '<a href="' . esc_url( add_query_arg( 'size_display', 'EU' ) ) . '">EU</a> '; | |
echo '<a href="' . esc_url( add_query_arg( 'size_display', 'US' ) ) . '">US</a> '; | |
echo '</div>'; | |
} | |
add_action( 'woocommerce_before_add_to_cart_form', 'size_switcher_display' ); | |
/** | |
* Switch size on demand. | |
*/ | |
function switch_size() { | |
if ( isset( $_GET['size_display'] ) && in_array( $_GET['size_display'], array( 'UK', 'EU', 'US' ) ) ) { | |
wc_setcookie( 'size_display', sanitize_text_field( $_GET['size_display'] ) ); | |
wp_safe_redirect( wp_get_referer() ); | |
exit; | |
} | |
} | |
add_action( 'wp', 'switch_size' ); | |
/** | |
* Convert UK size to X size. | |
*/ | |
function get_converted_size( $size, $target ) { | |
if ( 'US' === $target ) { | |
// US sizes are just 1 more. | |
$size ++; | |
} elseif ( 'EU' == $target ) { | |
// EU sizes are silly | |
switch ( $size ) { | |
case '6' : | |
return '40'; | |
break; | |
case '6.5' : | |
return '40.5'; | |
break; | |
case '7' : | |
return '41'; | |
break; | |
} | |
} | |
return $size; | |
} | |
/** | |
* Change size when set. Terms are for example, UK 7, UK 6.5 etc. | |
*/ | |
function get_term_switch_size( $_term, $taxonomy ) { | |
// Change when cookie is set, and not the default (UK can be left alone as that is the original). | |
if ( strstr( $_term->name, 'UK ' ) && isset( $_COOKIE['size_display'] ) && in_array( $_COOKIE['size_display'], array( 'EU', 'US' ) ) ) { | |
$term_name = explode( ' ', $_term->name ); | |
$new_size = get_converted_size( $term_name[1], $_COOKIE['size_display'] ); | |
// Change only if converted value was found. | |
if ( $new_size !== $term_name[1] ) { | |
$term_name[1] = $new_size; | |
$term_name[0] = $_COOKIE['size_display']; | |
$_term->name = implode( ' ', $term_name ); | |
} | |
} | |
return $_term; | |
} | |
add_filter( 'get_term', 'get_term_switch_size', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment