代码之家  ›  专栏  ›  技术社区  ›  Chris_1991_dk

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

  •  2
  • Chris_1991_dk  · 技术社区  · 8 年前

    在WooCommerce中,我目前正在使用一个功能,可以在页面访问时自动将特定产品(此处为产品ID 87)添加到购物车,使用 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 );
            }
        }
    }
    

    如何在此函数中从woocommerce动态获取最新的产品id,而不是特定的产品id?

    如有任何帮助或建议,将不胜感激。

    1 回复  |  直到 8 年前
        1
  •  0
  •   LoicTheAztec    8 年前

    这可以很容易地在代码段中包含一个简单的非常简单的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 );
    }
    

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

    从woocommerce 2.4版到最新版本均已测试并运行。