【问题标题】:how to sync a product in an iframe to the woocommerce cart如何将 iframe 中的产品同步到 woocommerce 购物车
【发布时间】:2015-05-05 15:52:38
【问题描述】:

我们目前正在升级我所在公司的网站。我们的旧网站上有一个嵌入 iframe 的产品设计师,并且设计的任何产品都会添加到购物篮中。

所以在新网站上我想要相同的 iframe,但我需要它来将设计的产品添加到 woocommerce 购物车。我只是想知道我是怎么做到的?

我不需要详细的解释,老实说,一些有用的链接就足够了。

感谢您及时的帮助!

【问题讨论】:

    标签: php wordpress iframe woocommerce


    【解决方案1】:

    我不能完全理解你的问题,但这里有两个基本的东西:

    第一件事:在 iframe 和主窗口之间传输数据: 你可以在这里阅读:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

    第二件事:通过代码将产品添加到woocommerce购物车:

        $product_id        = absint( $_POST['product_id']);
        $quantity          = empty( $_POST['quantity'] ) ? 1 : wc_stock_amount( $_POST['quantity'] );
        $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
        $product_status    = get_post_status( $product_id );
    
        if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity ) && 'publish' === $product_status ) {
    
            do_action('woocommerce_ajax_added_to_cart', $product_id);
    
        }
    

    有关 iframe postMessage 的更多信息(仅用于演示 - 安全是你的一部分):

    您想将数据从主窗口发送到 iframe。 准备好试试这个:

    document.getElementById('iframe').contentWindow.postMessage('hi', '*');
    

    在 iframe 窗口上试试这个:

    window.addEventListener("message", receiveMessage, false);
    
    function receiveMessage(event)
    {
        console.log(event.data);
    
    }
    

    您想将数据从 iframe 发送到主窗口:

    在 iframe 窗口上:

    window.parent.postMessage('hi', '*');
    

    在主窗口上:

    window.addEventListener("message", receiveMessage, false);
    
    function receiveMessage(event)
    {
        console.log(event.data);
    
    }
    

    希望有所帮助!

    【讨论】:

    • 如果您无法理解问题的答案,这可能是个坏主意,那么您应该在 cmets 中寻求澄清......
    • 谢谢,但我已经非常仔细地阅读了他的问题,所以我可以得到共同的想法。
    【解决方案2】:

    您需要在 iframe 中添加一个事件监听器并从 iframe 中输出数据。

    window.addEventListener('message', function(event) {
        iframeData = JSON.parse(event.data);
        //do something with iframeData
    }, false);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-21
      • 2021-08-22
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 2014-02-06
      • 2013-03-10
      • 1970-01-01
      相关资源
      最近更新 更多