在Woocommerce中自动添加购物车访问最新发布的产品

时间:2018-01-20 20:01:02

标签: php wordpress woocommerce cart product

在WooCommerce中,我目前正在使用this code snippet在页面访问时自动添加到购物车特定产品(此处为产品ID 87)的功能:

// 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 );
        }
    }
}

如何在此功能中动态获取woocommerce的最新产品ID,而不是特定的产品ID?

任何帮助或建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

可以轻松地在您的代码段中包含一个简单的非常轻松的SQL查询,该查询将获取上次发布的产品ID。

WC官方代码段已过时,$product->id已被$product->get_id()取代。

完成的重访代码:

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 );
}

代码进入活动子主题(或活动主题)的function.php文件。

从woocommerce版本2.4到最新版本进行测试和工作。