상품의 Custom Attribute 값 가져오기
우커머스내에서 상품의 Attribute 값을 필요에 따라 추가하여 활용하는 경우가 있습니다.
그리고 이 Attribute 값을 원하는 페이지에서 보여주고 싶을때가 있는데요.
그럴땐 아래 코드를 functions.php에 넣어 활용하시면 됩니다.
Attribute의 이름이 한글이어도 상관없습니다.
원래는 아래 블로그에서 찾은 내용인데, 숏코드 형태로 활용할 수 있도록 수정해보았습니다.
https://isabelcastillo.com/woocommerce-product-attributes-functions
function isa_woo_get_one_pa(){
// Edit below with the title of the attribute you wish to display
$desired_att = ‘Attribute 이름’;
global $product;
$attributes = $product->get_attributes();
if ( ! $attributes ) {
return;
}
$out = ”;
foreach ( $attributes as $attribute ) {
if ( $attribute[‘is_taxonomy’] ) {
// sanitize the desired attribute into a taxonomy slug
$tax_slug = strtolower(trim(preg_replace(‘/[^A-Za-z0-9-]+/’, ‘_’, $desired_att)));
// if this is desired att, get value and label
if ( $attribute[‘name’] == ‘pa_’ . $tax_slug ) {
$terms = wp_get_post_terms( $product->id, $attribute[‘name’], ‘all’ );
// get the taxonomy
$tax = $terms[0]->taxonomy;
// get the tax object
$tax_object = get_taxonomy($tax);
// get tax label
if ( isset ($tax_object->labels->name) ) {
$tax_label = $tax_object->labels->name;
} elseif ( isset( $tax_object->label ) ) {
$tax_label = $tax_object->label;
}
foreach ( $terms as $term ) {
$out .= $tax_label . ‘: ‘;
$out .= $term->name . ‘<br />’;
}
} // our desired att
} else {
// for atts which are NOT registered as taxonomies
// if this is desired att, get value and label
if ( $attribute[‘name’] == $desired_att ) {
$out .= $attribute[‘name’] . ‘: ‘;
$out .= $attribute[‘value’];
}
}
}
echo $out;
}
add_shortcode(‘숏코드_이름’, ‘isa_woo_get_one_pa’);
사용하실때는 [숏코드_이름] 으로 사용하시면 됩니다.
카트 페이지에서 Attribute 값이 보이도록 하려면 아래 코드를 functions.php 파일에 넣으시면 됩니다.
function isa_woo_cart_attributes($cart_item, $cart_item_key){
$item_data = $cart_item_key[‘data’];
$attributes = $item_data->get_attributes();
if ( ! $attributes ) {
return $cart_item;
}
$out = $cart_item . ‘<br />’;
foreach ( $attributes as $attribute ) {
if ( $attribute[‘is_taxonomy’] ) {
// skip variations
if ( $attribute[‘is_variation’] ) {
continue;
}
// backwards compatibility for attributes which are registered as taxonomies
$product_id = $item_data->id;
$terms = wp_get_post_terms( $product_id, $attribute[‘name’], ‘all’ );
// get the taxonomy
$tax = $terms[0]->taxonomy;
// get the tax object
$tax_object = get_taxonomy($tax);
// get tax label
if ( isset ($tax_object->labels->name) ) {
$tax_label = $tax_object->labels->name;
} elseif ( isset( $tax_object->label ) ) {
$tax_label = $tax_object->label;
}
foreach ( $terms as $term ) {
$out .= $tax_label . ‘: ‘;
$out .= $term->name . ‘<br />’;
}
} else {
// not a taxonomy
$out .= $attribute[‘name’] . ‘: ‘;
$out .= $attribute[‘value’] . ‘<br />’;
}
}
echo $out;
}
add_filter( ‘woocommerce_cart_item_name’, isa_woo_cart_attributes, 10, 2 );