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

概要

woocommerce_cart_contents 関数は、WooCommerceのカート内の商品の内容を取得するために使用されます。この関数は、カート内にある全アイテムの情報を配列として返します。主に以下のような場面で使われます。

  1. カートの合計金額を表示する。
  2. カートにある商品の情報をカスタマイズ表示する。
  3. 購入確認ページでカート内容を一覧表示する。
  4. カート内の商品数を表示するウィジェットを作成する。
  5. ユーザーのカートに基づいてダイナミックなコンテンツを生成する。
  6. 商品に対する特別な処理をカートが更新された時にトリガーする。

構文

$cart_contents = WC()->cart->get_cart();

パラメータ

この関数はパラメータを持ちません。

戻り値

カート内の商品を表す配列。各アイテムは、商品ID、数量、価格などの情報を含むオブジェクトで構成されています。

バージョン

  • WooCommerce:5.0以降
  • WordPress:5.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_contents');
function display_cart_contents() {
    $cart_contents = WC()->cart->get_cart();
    foreach ($cart_contents as $cart_item_key => $cart_item) {
        $product = $cart_item['data'];
        echo $product->get_name() . ' - ' . $cart_item['quantity'] . ' 個<br>';
    }
}

このコードは、カートの前にカート内の商品名と数量を表示します。woocommerce_before_cart フックを使用しています。

サンプル2: カート合計のカスタマイズ表示

add_action('woocommerce_cart_totals_after_order_total', 'custom_cart_total_display');
function custom_cart_total_display() {
    $cart_contents = WC()->cart->get_cart();
    $total_items = count($cart_contents);
    echo '<strong>カート内の商品数:</strong> ' . $total_items;
}

このコードは、カートの合計表示の後にカート内の商品数を表示します。woocommerce_cart_totals_after_order_total フックを使用しています。

サンプル3: カートの情報を取得しログに記録する

add_action('woocommerce_cart_updated', 'log_cart_contents');
function log_cart_contents() {
    $cart_contents = WC()->cart->get_cart();
    error_log(print_r($cart_contents, true));
}

このコードは、カートが更新されるたびにカートの内容をログに記録します。woocommerce_cart_updated フックを使用しています。

サンプル4: カートが空かどうかを確認する

add_action('woocommerce_before_cart', 'check_if_cart_is_empty');
function check_if_cart_is_empty() {
    if (WC()->cart->is_empty()) {
        echo 'カートは空です。';
    }
}

このコードはカートが空かどうかを確認し、空の場合にはメッセージを表示します。woocommerce_before_cart フックを使用しています。

サンプル5: カート内容に基づいて異なるメッセージを表示する

add_action('woocommerce_before_cart', 'show_custom_message_based_on_cart');
function show_custom_message_based_on_cart() {
    $cart_contents = WC()->cart->get_cart();
    if (count($cart_contents) > 5) {
        echo 'カートに商品が多すぎます!正確な購入を心がけてください。';
    }
}

このコードはカートに5個以上の商品がある場合にカスタムメッセージを表示します。woocommerce_before_cart フックを使用しています。

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


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