【问题标题】:How to properly initialize Woocommerce Cart如何正确初始化 Woocommerce 购物车
【发布时间】:2014-08-20 02:11:08
【问题描述】:

我有一个自定义模板文件,呈现一些产品及其添加到购物车按钮,我正在尝试手动实现。当按下 Add to Cart 时,页面会重新加载,并且包含一些数据的 $_POST 变量会添加新产品。 'cart_contents_count' 也反映了添加的项目。但是,当我转到购物车页面时,它是空的。请看以下代码。

global $woocommerce;
if ( isset( $_POST['AddedToCart'] ) ) {
$woocommerce->cart->add_to_cart($_POST['event'], $_POST['qty']);
}
$cart_total = $woocommerce->cart->cart_contents_count; 

但是,当我转到正常的默认商店页面 ( /shop/ ) 并从那里添加产品时,我的购物车页面显示该产品已被添加。当我现在转到我的自定义页面并从“添加到购物车”按钮添加产品​​时,它可以完美运行。

在我看来,在运行上述代码之前,我必须检查一个 Cart Session 是否已经初始化,如果没有,就初始化它。有人可以帮我确认我理解正确并告诉我如何初始化购物车吗?

【问题讨论】:

    标签: wordpress woocommerce cart


    【解决方案1】:

    在 WooCommerce 2.5 版中,它们改变了会话的工作方式。 https://woocommerce.wordpress.com/2015/10/07/new-session-handler-in-2-5/ 我所做的是安装这个插件https://github.com/kloon/woocommerce-large-sessions 然后我的购物车不再是空的猜测用户。

    我希望它可以帮助别人。

    【讨论】:

      【解决方案2】:

      如果您的自定义表单位于页面模板上,这是一个解决方案。此代码位于您的 functions.php 文件中。请务必将yourtheme_template 更改为更独特的内容。此外,将$session_templates 数组中的项目更改为您希望使用此过滤器的模板文件名。它使用template_include 过滤器,这不是一个容易追踪的过滤器,更不用说$woocommerce->session->set_customer_session_cookie(true) - 特别感谢@vrazer(在推特上)的帮助。

      function yourtheme_template($template) {
      
      //List of template file names that require WooCommerce session creation
      $session_templates = array(
          'page-template-file-name.php', 'another-page-template-filename.php'
      );
      
      //Split up the template path into parts so the template file name can be retrieved
      $parts = explode('/', $template);
      
      //Check the template file name against the session_templates list and instantiate the session if the
      //template is in the list and the user is not already logged in.  If the session already exists from
      //having created a cart, WooCommerce will not destroy the active session
       if (in_array($parts[count($parts) - 1], $session_templates)  && !is_user_logged_in()) {
       global $woocommerce;
      
        $woocommerce->session->set_customer_session_cookie(true);
       }
      
       return $template;
      }
      
      //Filter to run the WooCommerce conditional session instantiation code
      add_filter('template_include', 'yourtheme_template');
      

      【讨论】:

      • @Ardinent - 是的,特别是$woocommerce->session->set_customer_session_cookie(true);
      • 谢谢,在将产品添加到购物车之前设置 cookie 解决了问题。这应该是公认的答案
      • 设置全球 $woocommerce; $woocommerce->session->set_customer_session_cookie(true);在没有函数的 header.php 文件中也可以使用
      【解决方案3】:

      我通过确保$woocommerce->cart->add_to_cart() 行在发送任何标头之前定位来解决了这个问题。即,在我的自定义模板上调用 get_header() 之前。

      【讨论】:

        猜你喜欢
        • 2016-03-30
        • 2015-03-11
        • 2014-01-24
        • 1970-01-01
        • 2020-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多