2
votes

In WooCommerce, I am currently using a function that auto add to cart a specific product (here product ID 87) on page visit, using this code snippet:

// add item to cart on visit
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {

    if ( ! is_admin() ) {

        $product_id = 87;
        $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 );
        }
    }
}

How could I get dynamically the latest product id from woocommerce, in this function, instead of a specific product ID?

Any help or advice will be appreciated.

1

1 Answers

0
votes

This is possible easily including a simple very light SQL query in your code snippet that will get the last published product ID.

WC official code snippet is outdated as $product->id has been replaced by $product->get_id().

The completed revisited code:

add_action( 'template_redirect', 'auto_add_to_cart_last_product' );
function auto_add_to_cart_last_product() {
    if ( is_admin() ) return; // Not for admin area

    $cart = WC()->cart;
    global $wpdb;
    $found = false;

    // SQL Query: Get last published product ID
    $result = $wpdb->get_col(" SELECT ID FROM {$wpdb->prefix}posts
    WHERE post_type LIKE 'product'  AND post_status LIKE 'publish' ORDER BY ID DESC LIMIT 1");
    $newest_product_id = reset($result);

    // Check if product already in cart
    if ( ! $cart->is_empty() )
        foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
            // Added Woocommerce 3+ compatibility (as $product->id si outdated)
            $product_id = method_exists( $cart_item['data'], 'get_id' ) ? $cart_item['data']->get_id() : $cart_item['data']->id;
            if ( $product_id == $newest_product_id ){
                $found = true; // Found!
                break; // We exit from the loop
            }
        }

    // If product not found or if there is no product in cart, we add it.
    if ( ! $found || $cart->is_empty() )
        $cart->add_to_cart( $product_id );
}

Code goes in function.php file of your active child theme (or active theme).

Tested and works from woocommerce version 2.4 to lastest.