プラグインWooCommerceのwoocommerce_cart_contents_weight関数の使用方法・解説

概要

woocommerce_cart_contents_weight 関数は、WooCommerce ショッピングカート内の商品が持つ合計の重量を計算し、返すために使用されます。この関数は、特に実際の商品の配送コストを計算したり、商品の選択肢に基づいてユーザーに適切な情報を提供する際によく使用されます。以下に、具体的な使用例を挙げます。

  • 配送方法の選択を表示する際
  • 配送コストの計算
  • カートの商品情報の表示
  • 商品の重量に基づく割引プロモーション
  • 在庫管理システムとの統合
  • レポートや分析ツールでのデータ収集

構文

float woocommerce_cart_contents_weight();

パラメータ

この関数にはパラメータはありません。

戻り値

この関数は、カート内の全商品の合計重量を float 型で返します。

使用可能なプラグインバージョン

WooCommerce: 2.0 以降

使用可能な WordPress バージョン

WordPress: 4.0 以降

この関数のアクションでの使用可能性

アクション 使用例
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

  1. カートの合計重量を表示する

    add_action( 'woocommerce_before_cart', 'display_cart_weight' );
    
    function display_cart_weight() {
       $weight = WC()->cart->get_cart_contents_weight();
       echo '<p>カート内の合計重量: ' . esc_html( $weight ) . ' kg</p>';
    }
    

    このコードは、カートページの前にカート内の合計重量を表示します。

  2. 配送コスト計算に基づいてカートの重量を取得

    add_action( 'woocommerce_cart_calculate_fees', 'add_weight_based_shipping_fee' );
    
    function add_weight_based_shipping_fee() {
       $weight = WC()->cart->get_cart_contents_weight();
       if ( $weight > 10 ) {
           WC()->cart->add_fee( '重量割増料金', 5.00 );
       }
    }
    

    このコードは、カート内の商品の重量が10kgを超えた場合に追加の料金を感じる処理を行います。

  3. カート情報をJSONとして外部に出力

    add_action( 'wp_ajax_get_cart_weight', 'ajax_get_cart_weight' );
    
    function ajax_get_cart_weight() {
       $weight = WC()->cart->get_cart_contents_weight();
       echo json_encode( array( 'weight' => $weight ) );
       wp_die();
    }
    

    このコードはAJAXリクエストに応じてカートの重量をJSON形式で出力します。

  4. カートの重量に合わせてエラーメッセージを表示

    add_action( 'woocommerce_checkout_process', 'check_cart_weight_before_checkout' );
    
    function check_cart_weight_before_checkout() {
       $weight = WC()->cart->get_cart_contents_weight();
       if ( $weight > 20 ) {
           wc_add_notice( 'カートの重さは20kgを超えています。', 'error' );
       }
    }
    

    このコードは、チェックアウト時にカートの重量が20kgを超えるとエラーメッセージを表示します。

  5. カートの合計重量を管理者に通知する

    add_action( 'admin_notices', 'notify_cart_weight_to_admin' );
    
    function notify_cart_weight_to_admin() {
       if ( ! is_admin() ) return;
       $weight = WC()->cart->get_cart_contents_weight();
       echo '<div class="notice notice-info"><p>現在のカート重量: ' . esc_html( $weight ) . ' kg</p></div>';
    }
    

    このコードは、管理者ダッシュボードに現在のカートの合計重量を通知します。

この関数について質問する


上の計算式の答えを入力してください