无法在我的自定义php文件中调用WooCommerce钩子

时间:2020-04-06 作者:Muhammad Husanin Zafar

It is not a plugin, it is just a simple file call on ajax.

我的Js代码

$(\'.pkg-btn\').click(function(){
    var this_id = $(this).parent().attr(\'id\');
    var url = templateUrl+\'/tw-add-to-cart-ajax.php\';
    $.ajax({
        type: \'POST\',
        url: url,
        data: ({selected_package_id: this_id}),
        dataType: \'json\',
        success: function(data1) {
            console.log(data1);
            $(\'#conditions\').show();
        }
    });
});
我的php文件代码

<?php

//        $product_id = $_POST[\'selected_package_id\'];
//        echo $product_id; // It displays id - works fine here
//        exit();

    add_action(\'woocommerce_add_to_cart\', \'custome_add_to_cart\');

    function custome_add_to_cart() {

         echo \'hook called\'; // This is not showing any message
         exit();

        global $woocommerce;
        $product_id = $_POST[\'selected_package_id\'];

        echo $product_id; // This is not displaying id
        exit();

        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values[\'data\'];
                if ( $_product->id == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found ){
                WC()->cart->add_to_cart( $product_id );
            }
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
在调用hook之前,我在php文件中获得传递的id并对其进行回显。它显示id,意味着js将数据传递给php,php也会获得该id,但当我调用hook时,它显示错误:jquery-3.4.1.min.js:2 POST domain-url/wp-content/themes/my-theme-folder/tw-add-to-cart-ajax.php 500 (Internal Server Error) 并在网络中显示消息This request has no response data available

1 个回复
SO网友:BlueSuiter

您完全做错了,请在文件中按以下方式放置代码。

<?php

echo \'hook called\'; // This is not showing any message
    exit();

global $woocommerce;
$product_id = $_POST[\'selected_package_id\'];

echo $product_id; // This is not displaying id
exit();

$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
    foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $_product = $values[\'data\'];
        if ( $_product->id == $product_id )
            $found = true;
    }
    // if product not found, add it
    if ( ! $found ){
        WC()->cart->add_to_cart( $product_id );
    }
} else {
    // if no products in cart, add it
    WC()->cart->add_to_cart( $product_id );
}
您使用的钩子方法是不正确的。

相关推荐

400个错误请求进入AJAX调用

我尝试,当单击submit按钮时,用一些值传递ajax请求,然后计算这些值并返回。My Problem : 当我进行自定义Ajax调用时,我从管理Ajax得到400个错误。php。请帮我找出我的错误或最好的方法来做这件事。Ajax Call - footer.php(theme footer) <script> $(function() { $(\"#calc_form\").on(\"submit\", function(e) {