Reputation: 2098
I am trying to call a custom function in function.php on POST submit button in wordpress. Bellow you can see if statement when i remove it function call work's perfectly but with if statement it's not work when I am post i am reached in if statement but not able to call the function.
if (isset($_POST['addcustomcarts']))
{
echo("if");
add_filter('woocommerce_before_cart', 'customcart');
//global $woocommerce;
function customcart() {
global $woocommerce;
$my_post = array(
'post_title' => 'My post',
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_type' =>'product'
);
echo"sdafsdf";
// 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);
$woocommerce->cart->add_to_cart( $product_ID, $quantity=1 );
//exit;
//header("Location: http://www.mydomain.com");exit();
wp_redirect(".home_url('cart').");
//wp_redirect(home_url());
//global $wpdb;
//$wpdb->query
//exit;
//exit;
}
}
Upvotes: 0
Views: 5617
Reputation: 2098
I have solve the issue use add_action('init', 'customcart');
instead of add_filter('woocommerce_before_cart', 'customcart');
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' ) ) ) );
}
}
}
Upvotes: 0
Reputation: 5856
You need to remove the whole function from the if statement and only call the action. Like this:
if (isset($_POST['addcustomcarts']))
{
echo("if");
add_filter('woocommerce_before_cart', 'customcart');
//global $woocommerce;
}
function customcart() {
global $woocommerce;
$my_post = array(
'post_title' => 'My post',
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_type' =>'product'
);
echo"sdafsdf";
// 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);
$woocommerce->cart->add_to_cart( $product_ID, $quantity=1 );
//exit;
//header("Location: http://www.mydomain.com");exit();
wp_redirect(".home_url('cart').");
//wp_redirect(home_url());
//global $wpdb;
//$wpdb->query
//exit;
//exit;
}
Upvotes: 1