logo
down
shadow

Check and Add To Cart depending on Items


Check and Add To Cart depending on Items

By : user2954604
Date : November 22 2020, 10:31 AM
help you fix your problem Assuming your original code works, here is how I would do it. I have renamed a variable or two for ease of reading.
code :
$product_1_in_cart = false;
$product_2_in_cart = false;

if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
        $_product = $values['data'];
        if ( $_product->id == $product1_id )
            $product_1_in_cart = true;
        if ( $_product->id == $product2_id )
            $product_2_in_cart = true;
    }
    // if product 1 is in cart, and product 2 is not in cart
    if ( $product_1_in_cart && !$product_2_in_cart ){
        $woocommerce->cart->add_to_cart( $product2_id );
    }
} else {

}


Share : facebook icon twitter icon
Magento cart items check

Magento cart items check


By : Martin Fink
Date : March 29 2020, 07:55 AM
I wish this helpful for you How can I check if all the cart items have my custom attribute? And if item/items all have the custom attribute prints a message but if one of the cart item/items doesn't have the custom attribute, it prints an error message in the checkout? , Please try below code
code :
<?php
$productModel = Mage::getModel('catalog/product');
$cart = Mage::getModel('checkout/cart')->getQuote();
$error = "";
foreach ($cart->getAllItems() as $item) {
    $product = $productModel->load($item->getProduct()->getId());
    if($product->getData('your_attribute_code')){
        $message = "your message for items have attribute";
        $error = 0;
    }else{
        $message = "your message for items have no attributes";
        $error = 1;
        break;
    }
}
if($error == 1){
    Mage::getSingleton('core/session')->addError($message);
}else{
    Mage::getSingleton('core/session')->addSuccess($message);   
}

?>
WooCommerce: Check if items are already in cart

WooCommerce: Check if items are already in cart


By : manish
Date : March 29 2020, 07:55 AM
it helps some times
global $woocommerce and $woocommerce->cart is outdated and simply replaced by WC()->cart
code :
function matched_cart_items( $search_products ) {
    $count = 0; // Initializing

    if ( ! WC()->cart->is_empty() ) {
        // Loop though cart items
        foreach(WC()->cart->get_cart() as $cart_item ) {
            // Handling also variable products and their products variations
            $cart_item_ids = array($cart_item['product_id'], $cart_item['variation_id']);

            // Handle a simple product Id (int or string) or an array of product Ids 
            if( ( is_array($search_products) && array_intersect($search_products, cart_item_ids) ) 
            || ( !is_array($search_products) && in_array($search_products, $cart_item_ids)
                $count++; // incrementing items count
        }
    }
    return $count; // returning matched items count 
}
$product_id = 102;

// Usage as a condition in an if statement
if( 0 < matched_cart_items($product_id) ){
    echo '<p>There is "'. matched_cart_items($product_id) .'"matched items in cart</p><br>';
} else {
    echo '<p>NO matched items in cart</p><br>';
}
$product_ids = array(102,107,118);

// Usage as a condition in an if statement
if( 0 < matched_cart_items($product_ids) ){
    echo '<p>There is "'. matched_cart_items($product_ids) .'"matched items in cart</p><br>';
} else {
    echo '<p>NO matched items in cart</p><br>';
}
$product_ids = array(102, 107, 118, 124, 137);

// Usage as a condition in an if statement (for 3 matched items or more)
if( 3 <= matched_cart_items($product_ids) ){
    echo '<p>There is "'. matched_cart_items($product_ids) .'"matched items in cart</p><br>';
} else {
    echo '<p>NO matched items in cart</p><br>';
}
Check if there are out of stock items in cart - WooCommerce

Check if there are out of stock items in cart - WooCommerce


By : Jinson Joseph
Date : March 29 2020, 07:55 AM
This might help you You can do it like this to check against the "Stock quantity" and the "Allow Backorders?" properties of the products:
code :
function notes_in_cart() {
     global $woocommerce;

    if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }

    if ( WC()->cart->needs_shipping() ){

        // set $out_of_stock_exists to false by default
        $out_of_stock_exists = false;
        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
            if($values['data']->backorders_allowed()){ //check if backorders are allowed on this product
                // get the stock quantity - returns the available amount number
                $stock_info = $values['data']->get_stock_quantity();

                if($stock_info < $values['quantity']){ //thanks to LoicTheAztec for pointing it out in his answer
                    // set $out_of_stock_exists to true and stop foreach execution
                    $out_of_stock_exists = true;
                    break;
                }
            }

        }

        //if cart has items out of stock
        if ($out_of_stock_exists) {
            ?>
            <tr class="ceckoutStockMeta">
                <th>Item Shipments</th>
                <td>
                    <p style="color: red;">*You have one or more items in your cart that are currently out of stock. Please select a custom shipping option for your order.</p><br>
                    <form>

                        <input type="radio" name="stockOp" id="stockOption1" value="ship" />
                        <label for="stockOption1">Ship what is available now</label><br>

                        <input type="radio" name="stockOp" id="stockOption2" value="hold" />
                        <label for="stockOption2">Wait and ship together</label>
                    </form>
                </td>
            </tr>

            <?php

        }
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'notes_in_cart' );
add_action( 'woocommerce_review_order_after_order_total', 'notes_in_cart' );
public function is_in_stock() {
    return apply_filters( 'woocommerce_product_is_in_stock', 'instock' === $this->get_stock_status(), $this );
}
Check for Product Category in cart items with WooCommerce

Check for Product Category in cart items with WooCommerce


By : user2320733
Date : March 29 2020, 07:55 AM
it helps some times I'm trying to make a condition, where a function displays on WooCommerce checkout page only, if any product from category ilutulestik is present in the shopping cart. , The correct way for cart items to be used with product categories is:
code :
add_action('woocommerce_before_cart', 'action_before_cart');
function action_before_cart() {
    $categories   = array('ilutulestik-2');
    $has_category = false;

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // Check for product categories
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $has_category = true;
            break;
        }
    }

    // Testing output (display a notice)
    if ( $has_category ) { 
        wc_print_notice( sprintf( 'Product category "%s" is in cart!', reset($categories)), 'notice' );
    }
}
// Custom conditional function that checks for parent product categories
function has_product_categories( $product_id, $categories ) {
     // Initializing
    $parent_term_ids = $categories_ids = array();
    $taxonomy        = 'product_cat';

    // Convert categories term names and slugs to categories term ids
    foreach ( $categories as $category ){
        if( is_numeric( $category ) ) {
            $categories_ids[] = (int) $category;
        } elseif ( term_exists( sanitize_title( $category ), $taxonomy ) ) {
            $categories_ids[] = get_term_by( 'slug', sanitize_title( $category ), $taxonomy )->term_id;
        }
    }

    // Loop through the current product category terms to get only parent main category term
    foreach( get_the_terms( $product_id, $taxonomy ) as $term ){
        if( $term->parent > 0 ){
            $parent_term_ids[] = $term->parent; // Set the parent product category
            $parent_term_ids[] = $term->term_id; // (and the child)
        } else {
            $parent_term_ids[] = $term->term_id; // It is the Main category term and we set it.
        }
    }
    return array_intersect( $categories_ids, array_unique($parent_term_ids) ) ? true : false;
}

add_action('woocommerce_before_cart', 'action_before_cart');
function action_before_cart() {
    $categories   = array('ilutulestik-2');
    $has_category = false;

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // Check for product categories
        if ( has_product_categories( $cart_item['product_id'], $categories ) ) {
            $has_category = true;
            break;
        }
    }

    // Testing output (display a notice)
    if ( $has_category ) {
        wc_print_notice( sprintf( 'Product category "%s" is in cart!', reset($categories)), 'notice' );
    }
}
Magento Cart: Check for items empties cart

Magento Cart: Check for items empties cart


By : justmeettheman
Date : March 29 2020, 07:55 AM
this one helps. The problem is in event, that you are observing. Because Magento session wasn't initialized at that moment, so cookie has different name, than core one.
Use controller_action_predispatch for setting up some session data from request.
Related Posts Related Posts :
  • php curl headers do not return from website?
  • How to find out, if facebook ID is a user, group or page
  • Connect webhost database to android database
  • preg_match get div content with class
  • Upload multiple files in Laravel 4
  • Count array numbers in multidimensional array
  • PHP Date diff with a difference
  • Search Customer by custom field in Netsuite
  • Is it possible to hide/encode/encrypt php source code and let others have the system?
  • list items to be displayed using php code and array
  • check if row exists mysqli
  • PHP errors loading MySQL
  • setup PostgreSQL with Laravel in MAMP
  • PHP - CodeIgniter Notifications
  • Encrypting a password column in a SQL database
  • New to PHP, trying to extract information from another website
  • JavaScript AmChart to Image for Email
  • Is javascript validation enough to keep my forms secure?
  • Regex extract variables from [shortcode]
  • Download a .mp3 link and save it to computer with PHP
  • Error with the ereg_replace
  • Getting the fields attached to a bundle of an entity in Drupal
  • Php how to check multiple times (within `foreach`) if values from array exists in mysql?
  • MySQL and PHP parsing strange string
  • Pull specific data from multidimensional associative array
  • How to get the original URI extension using PHP Tonic?
  • Upload videos and images from Android to PHP server?
  • Unset a multidimensional array with another multidimensional array with values than key
  • Calling a user e-mail to add to a mailto link PHP
  • Why is override_function coming back as an undefined function
  • PHP mySQLi_fetch_all: iterate through each row
  • Using pow in php
  • What's wrong with my PHP Script? T_String issue
  • how to call a function of another file without including that file
  • is_rgb function in php
  • transform the numbers to letters using php
  • How to catch an exception from another class method PHP
  • PHP exec is blocked by ISP
  • PHP4 to PHP5 migration character encoding. latin1 vs utf8
  • Begin Transaction not defined
  • How much harm can a user do with xss on a page unique to them?
  • How to import data from a php file to javascript variable
  • PHP and Javascript - log complete workflow
  • When I echo !!! 0 it gives me a strange result
  • jquery ajax post dies after submit
  • How to upload file with curl on sftp server
  • Advanced search using a text input to search through only one category
  • Why do I get "Non-static method App\Models\Category::products() should not be called statically" in laravel
  • Stop notices from undefined indexes in arrays
  • PHP Excel Error when entering SUM function to a cell
  • laravel 4 eloquent eager load relation count
  • click submit in html and run php code
  • Extremely frustrating behavior with Internet Explorer, Bootstrap and Respond.js
  • Vkontakte vtag issues
  • Divide the number to a correct decimal
  • mysqli_insert_query not working
  • How to make a sitemap using zend framework 1
  • Laravel: array to Model with relationship tree
  • $_SERVER['DOCUMENT_ROOT'] vs $path = $_SERVER['DOCUMENT_ROOT']
  • What is the best way to store multiple checkbox values in the database and work with it later on
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org