我正在定制woo commerce插件,将产品从前端添加到购物车中。我已经在函数中编写了函数。php,但我遇到了一个致命错误。
获取此错误-->
致命错误:在C:\\wamp\\www\\cutting-edge\\u server\\wordpress\\u theme\\wp content\\themes\\cutting\\u age\\responsive\\functions中的非对象上调用成员函数add\\u to\\u cart()。php在线56
有人知道怎么解决吗?
我的职能。php文件
if (isset($_POST["addcustomcarts"]))
{
echo $_SERVER[QUERY_STRING];
// echo $_SERVER[REQUEST_URI];
echo "i am in if";
//exit();
add_filter(\'woocommerce_before_cart\', \'customcart\');
function customcart() {
echo "i am in function";
//global $woocommerce;
$my_post = array(
\'post_title\' => \'My post\',
\'post_content\' => \'This is my post.\',
\'post_status\' => \'publish\',
\'post_author\' => 1,
\'post_type\' =>\'product\'
);
// Insert the post into the database
$product_ID=wp_insert_post( $my_post );
add_post_meta($product_ID, \'_regular_price\', 100, $unique);
add_post_meta($product_ID, \'_price\', 100, $unique);
add_post_meta($product_ID, \'_stock_status\', \'instock\', $unique);
//Getting error on this line.
$woocommerce->cart->add_to_cart( $product_ID, $quantity=1 );
exit( wp_redirect( home_url( "cart" ) ) );
}
customcart();
}
我的html文件
<form name="addpro" method="post" action="">
<input type="submit" name="addcustomcarts" value="ADD TOO CART" />
</form>
最合适的回答,由SO网友:helgatheviking 整理而成
我不确定您到底在做什么,但下面的代码确实对我有用,因为它创建了一个新产品并将其添加到购物车中。注意,我必须使用$_GET
在我的设置上进行测试,因为我没有您的其余代码,也不想创建表单。
EDIT: 我添加了一个简单的<form>
元素并切换到$_POST
. EDIT 2: 我已经删除了表单。很明显,OP的表格在头版。
add_action(\'init\', \'customcart\');
function customcart() {
if (isset($_POST["addcustomcarts"])) {
global $woocommerce;
$my_post = array(
\'post_title\' => \'My post\',
\'post_content\' => \'This is my post.\',
\'post_status\' => \'publish\',
\'post_author\' => 1,
\'post_type\' =>\'product\'
);
// Insert the post into the database
$product_ID = wp_insert_post( $my_post );
if ( $product_ID ){
add_post_meta($product_ID, \'_regular_price\', 100 );
add_post_meta($product_ID, \'_price\', 100 );
add_post_meta($product_ID, \'_stock_status\', \'instock\' );
//Getting error on this line.
$woocommerce->cart->add_to_cart( $product_ID, $quantity=1 );
exit( wp_redirect( get_permalink( woocommerce_get_page_id( \'cart\' ) ) ) );
}
}
}