Ich passe das Woo-Commerce-Plugin an, um das Produkt vom Front-End in den Warenkorb zu legen. Ich habe die Funktion in functions.php geschrieben, aber ich erhalte einen schwerwiegenden Fehler.
Diesen Fehler bekommen ->
Schwerwiegender Fehler: Rufen Sie eine Mitgliedsfunktion add_to_cart () für ein Nicht-Objekt in auf
C:\wamp\www\schneidserver\wordpress_theme\wp-content\themes\schneidseite\responsive\functions.php in Zeile 56
Hat jemand eine Idee, wie man es lösen kann?
Meine function.php Datei
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();
}
Meine HTML-Datei
<form name="addpro" method="post" action="">
<input type="submit" name="addcustomcarts" value="ADD TOO CART" />
</form>
Ich bin nicht sicher, was Sie genau tun, aber der folgende Code hat für mich funktioniert, da er ein neues Produkt erstellt und in den Warenkorb gelegt hat. Hinweis: Ich musste $_GET
verwenden, um mein Setup zu testen, da ich den Rest Ihres Codes nicht habe und keine Lust hatte, ein Formular zu erstellen.
EDIT: Ich habe ein einfaches <form>
-Element hinzugefügt und zu $_POST
gewechselt. EDIT 2 : Ich habe das Formular entfernt. Anscheinend hat das OP das Formular auf der Titelseite.
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' ) ) ) );
}
}
}
Der Warenkorb von $ woocommerce-> ist anscheinend kein Objekt während des Anrufs. Stellen Sie es so ein, dass es vor der fehlerhaften Zeile geprüft wird:
if( $woocommerce->cart )
$woocommerce->cart->add_to_cart( $product_ID, $quantity=1 );
Dies stellt sicher, dass der Wagen gerade ist und führt die Zeile nicht aus, wenn dies nicht der Fall ist.