우커머스의 주문 매출 실적, 상품매출실적, 고객별 매출실적 등의 데이터를 구글 어날리틱스에서 수집해 분석을 할 수 있다. 대부분의 구글 어날리틱스 플러그인들이 유료로 이 전자상거래 기능을 제공해주는데, 따로 유료기능을 이용할 필요없이 간단히 아래 코드를 functions.php 파일에 붙여넣어주면 구글 어날리틱스에서 전자상거래 정보를 확인 할 수 있다.
참고로 코드에서 name, brand 부분은 자신의 사이트에 맞게 고쳐주면 된다.
This file contains 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
add_action( 'woocommerce_thankyou', 'sbl_wc_ga_integration' ); | |
function sbl_wc_ga_integration( $order_id ) { | |
$order = new WC_Order( $order_id ); ?> | |
<script type="text/javascript"> | |
gtag('event', 'purchase', { | |
"transaction_id": "<?php echo $order_id;?>", | |
"affiliation": "<?php echo get_option( 'blogname' );?>", | |
"value": "<?php echo $order->get_total();?>", | |
"currency": "<?php echo get_woocommerce_currency();?>", | |
"tax": "<?php echo $order->get_total_tax();?>", | |
"shipping": "<?php echo $order->get_total_shipping();?>", | |
"items": [ | |
<?php | |
// Item Details | |
if ( sizeof( $order->get_items() ) > 0 ) { | |
foreach( $order->get_items() as $item ) { | |
$product_cats = get_the_terms( $item['product_id'], 'product_cat' ); | |
if ($product_cats) { | |
$cat = $product_cats[0]; | |
} ?> | |
{ | |
"id": "<?php echo get_post_meta($item['product_id'], '_sku', true);?>", | |
"name": "<?php echo $item['name'].' / '.get_field('item_color',$item['product_id']);?>", | |
"list_name": "<?php echo get_option( 'blogname' );?>", | |
"brand": "SMILEBOYLAB", | |
"category": "<?php echo $cat->name;?>", | |
"variant": "<?php echo get_field('item_color',$item['product_id']);?>", | |
"quantity": "<?php echo $item['qty'];?>", | |
"price": "<?php echo $item['line_subtotal'];?>" | |
}, | |
<?php | |
} | |
} ?> | |
] | |
}); | |
</script> | |
<?php | |
} |