自学内容网 自学内容网

wordpress woocommer 添加代码实现,点击按钮,将产品添加到购物车并且跳转到结账页面

wordpress woocommer 添加代码实现,点击按钮,将产品添加到购物车并且跳转到结账页面

案列代码1,解决的是普通产品的

//短代码生成按钮,传入短代码,点击直接到达结账页面
function add_product_to_cart_button($atts) {
    // 定义默认值
    $defaults = array(
        'id' => null,
        'label' => '立即购买',
    );

    // 使用 shortcode_atts 处理用户传入的参数
    $atts = shortcode_atts($defaults, $atts, 'add_to_cart_button');

    // 获取参数值
    $product_id = $atts['id'];
    $button_label = $atts['label'];

    // 检查产品ID是否有效
    if (!$product_id || !is_numeric($product_id)) {
        return '无效的产品ID。';
    }

    // 生成按钮HTML
    $button_html = sprintf(
        '<form class="add_to_cart_form" method="post" action="%s">
            <input type="hidden" name="action" value="add_to_cart_and_checkout" />
            <input type="hidden" name="product_id" value="%d" />
            <button type="submit" class="button">%s</button>
        </form>',
        esc_url(admin_url('admin-post.php')),
        intval($product_id),
        esc_html($button_label)
    );

    return $button_html;
}

// 注册短代码
add_shortcode('add_to_cart_button', 'add_product_to_cart_button');

function handle_add_to_cart_and_checkout() {
    // 确保 WooCommerce 环境已加载
    if (!function_exists('wc')) {
        include_once ABSPATH . 'wp-content/plugins/woocommerce/includes/wc-core-functions.php';
    }

    // 初始化 WooCommerce 购物车
    if (function_exists('wc_load_cart')) {
        wc_load_cart();
    }

    // 获取产品ID
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;

    // 检查产品ID是否有效
    if ($product_id > 0 && WC()->cart) {
        // 检查购物车中是否已经存在产品
        $cart_contains_product = false;
        foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
            if ($cart_item['product_id'] == $product_id) {
                // 如果购物车中已经存在相同的产品,则增加产品数量
                WC()->cart->set_quantity($cart_item_key, $cart_item['quantity'] + 1);
                $cart_contains_product = true;
                break;
            }
        }

        // 如果购物车中不存在相同的产品,则添加新产品到购物车
        if (!$cart_contains_product) {
            // 添加产品到购物车
            WC()->cart->add_to_cart($product_id);
        }
    }

    // 跳转到结账页面
    wp_safe_redirect(wc_get_checkout_url());
    exit;
}

// 注册处理表单提交的操作
add_action('admin_post_nopriv_add_to_cart_and_checkout', 'handle_add_to_cart_and_checkout');
add_action('admin_post_add_to_cart_and_checkout', 'handle_add_to_cart_and_checkout');

在前台使用段代码

[add_to_cart_button id="213148" label="buy now"]

下面是案列代码2,解决的是复杂产品的

//短代码生成按钮,传入短代码,点击直接到达结账页面
function add_product_to_cart_button($atts) {
    // 定义默认值
    $defaults = array(
        'id' => null,
        'label' => '立即购买',
    );

    // 使用 shortcode_atts 处理用户传入的参数
    $atts = shortcode_atts($defaults, $atts, 'add_to_cart_button');

    // 获取参数值
    $product_id = $atts['id'];
    $button_label = $atts['label'];

    // 检查产品ID是否有效
    if (!$product_id || !is_numeric($product_id)) {
        return '无效的产品ID。';
    }

    // 获取产品对象
    $product = wc_get_product($product_id);
    if (!$product) {
        return '产品不存在。';
    }

    // 如果产品是变体产品,获取变体信息
    $variation_fields = '';
    if ($product->is_type('variable')) {
        // 获取所有变体
        $available_variations = $product->get_available_variations();
        if (!empty($available_variations)) {
            $variation_fields .= '<select name="variation_id">';
            $variation_fields .= '<option value="">' . __('Choose an option', 'woocommerce') . '</option>';
            foreach ($available_variations as $variation) {
                $variation_id = $variation['variation_id'];
                $variation_label = implode(' / ', $variation['attributes']);
                $variation_fields .= '<option value="' . $variation_id . '">' . $variation_label . '</option>';
            }
            $variation_fields .= '</select>';
        }
    }

    // 生成按钮HTML
    $button_html = sprintf(
        '<form class="add_to_cart_form" method="post" action="%s">
            <input type="hidden" name="action" value="add_to_cart_and_checkout" />
            <input type="hidden" name="product_id" value="%d" />
            %s
            <button type="submit" class="button">%s</button>
        </form>',
        esc_url(admin_url('admin-post.php')),
        intval($product_id),
        $variation_fields,
        esc_html($button_label)
    );

    return $button_html;
}

// 注册短代码
add_shortcode('add_to_cart_button', 'add_product_to_cart_button');
function handle_add_to_cart_and_checkout() {
    // 确保 WooCommerce 环境已加载
    if (!function_exists('wc')) {
        include_once ABSPATH . 'wp-content/plugins/woocommerce/includes/wc-core-functions.php';
    }

    // 初始化 WooCommerce 购物车
    if (function_exists('wc_load_cart')) {
        wc_load_cart();
    }

    // 获取产品ID和变体ID
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    $variation_id = isset($_POST['variation_id']) ? intval($_POST['variation_id']) : 0;

    // 检查产品ID是否有效
    if ($product_id > 0 && WC()->cart) {
        // 添加产品到购物车
        WC()->cart->add_to_cart($product_id, 1, $variation_id);

        // 跳转到结账页面
        wp_safe_redirect(wc_get_checkout_url());
        exit;
    } else {
        // 如果产品ID无效,返回错误信息
        wp_die('无效的产品ID。');
    }
}

// 注册处理表单提交的操作
add_action('admin_post_nopriv_add_to_cart_and_checkout', 'handle_add_to_cart_and_checkout');
add_action('admin_post_add_to_cart_and_checkout', 'handle_add_to_cart_and_checkout');

<style>
.add_to_cart_form {
text-align: center;
}
.add_to_cart_form button {
background-color: #1F2E5C;
width:141px;
color:#ffffff;
height:46px;
line-height:46px;
margin:auto;
margin-top:20px;
}
</style>

最终的代码,简单的产品直接加入购物车,复杂的产品是点击按钮以后,隐藏掉第一个按钮,显示第二个按钮和输入框

// 引入需要的js
function custom_enqueue_scripts() {
    wp_enqueue_script('custom-variation-selector', get_template_directory_uri() . '/js/custom-variation-selector.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');

// 短代码生成按钮,传入短代码,点击直接到达结账页面
function add_product_to_cart_button($atts) {
    // 定义默认值
    $defaults = array(
        'id' => null,
        'label' => '立即购买',
    );

    // 使用 shortcode_atts 处理用户传入的参数
    $atts = shortcode_atts($defaults, $atts, 'add_to_cart_button');

    // 获取参数值
    $product_id = $atts['id'];
    $button_label = $atts['label'];

    // 检查产品ID是否有效
    if (!$product_id || !is_numeric($product_id)) {
        return '无效的产品ID。';
    }

    // 获取产品对象
    $product = wc_get_product($product_id);
    if (!$product) {
        return '产品不存在。';
    }

    // 如果产品是变体产品,获取变体信息
    $variation_fields = '';
    if ($product->is_type('variable')) {
        // 获取所有变体
        $available_variations = $product->get_available_variations();
        if (!empty($available_variations)) {
            $variation_fields .= '<select name="variation_id" id="variation_select_' . $product_id . '" style="display:none;">';
            $variation_fields .= '<option value="">' . __('Choose an option', 'woocommerce') . '</option>';
            foreach ($available_variations as $variation) {
                $variation_id = $variation['variation_id'];
                $variation_label = implode(' / ', $variation['attributes']);
                $variation_fields .= '<option value="' . $variation_id . '">' . $variation_label . '</option>';
            }
            $variation_fields .= '</select>';
        }
    }

    // 生成按钮HTML
    $button_html = sprintf(
        '<form class="add_to_cart_form" method="post" action="%s" id="add_to_cart_form_%d">
            <input type="hidden" name="action" value="add_to_cart_and_checkout" />
            <input type="hidden" name="product_id" value="%d" />
            %s
            <button type="button" class="button" id="initial_button_%d" οnclick="showVariationSelector(%d)">%s</button>
            <button type="submit" class="button" id="submit_button_%d" style="display:none;">%s</button>
        </form>',
        esc_url(admin_url('admin-post.php')),
        intval($product_id),
        intval($product_id),
        $variation_fields,
        intval($product_id),
        intval($product_id),
        esc_html($button_label),
        intval($product_id),
        esc_html($button_label)
    );

    return $button_html;
}

// 注册短代码
add_shortcode('add_to_cart_button', 'add_product_to_cart_button');

function handle_add_to_cart_and_checkout() {
    // 确保 WooCommerce 环境已加载
    if (!function_exists('wc')) {
        include_once ABSPATH . 'wp-content/plugins/woocommerce/includes/wc-core-functions.php';
    }

    // 初始化 WooCommerce 购物车
    if (function_exists('wc_load_cart')) {
        wc_load_cart();
    }

    // 获取产品ID和变体ID
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    $variation_id = isset($_POST['variation_id']) ? intval($_POST['variation_id']) : 0;

    // 检查产品ID是否有效
    if ($product_id > 0 && WC()->cart) {
        // 获取购物车中的所有项目
        $cart = WC()->cart->get_cart();

        // 检查购物车中是否已有此产品
        $product_exists_in_cart = false;
        foreach ($cart as $cart_item_key => $cart_item) {
            if ($cart_item['product_id'] === $product_id && $cart_item['variation_id'] === $variation_id) {
                // 更新购物车中的产品数量
                WC()->cart->set_quantity($cart_item_key, $cart_item['quantity'] + 1);
                $product_exists_in_cart = true;
                break;
            }
        }

        // 如果购物车中没有此产品,则添加
        if (!$product_exists_in_cart) {
            WC()->cart->add_to_cart($product_id, 1, $variation_id);
        }

        // 跳转到结账页面
        wp_safe_redirect(wc_get_checkout_url());
        exit;
    } else {
        // 如果产品ID无效,返回错误信息
        wp_die('无效的产品ID。');
    }
}

// 注册处理表单提交的操作
add_action('admin_post_nopriv_add_to_cart_and_checkout', 'handle_add_to_cart_and_checkout');
add_action('admin_post_add_to_cart_and_checkout', 'handle_add_to_cart_and_checkout');

下面是对应的js代码

document.addEventListener('DOMContentLoaded', function() {
    window.showVariationSelector = function(productId) {
        var variationSelector = document.getElementById('variation_select_' + productId);
        var initialButton = document.getElementById('initial_button_' + productId);
        var submitButton = document.getElementById('submit_button_' + productId);

        if (variationSelector) {
            variationSelector.style.display = 'block';
            initialButton.style.display = 'none';
            submitButton.style.display = 'inline-block';
        } else {
            // 如果没有变体选择器,直接提交表单
            document.getElementById('add_to_cart_form_' + productId).submit();
        }
    };
});

输入框显示在,按钮的下方的(这种情况的代码)

// 引入需要的js
function custom_enqueue_scripts() {
    wp_enqueue_script('custom-variation-selector', get_template_directory_uri() . '/js/custom-variation-selector.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');

// 短代码生成按钮,传入短代码,点击直接到达结账页面
function add_product_to_cart_button($atts) {
    // 定义默认值
    $defaults = array(
        'id' => null,
        'label' => '立即购买',
    );

    // 使用 shortcode_atts 处理用户传入的参数
    $atts = shortcode_atts($defaults, $atts, 'add_to_cart_button');

    // 获取参数值
    $product_id = $atts['id'];
    $button_label = $atts['label'];

    // 检查产品ID是否有效
    if (!$product_id || !is_numeric($product_id)) {
        return '无效的产品ID。';
    }

    // 获取产品对象
    $product = wc_get_product($product_id);
    if (!$product) {
        return '产品不存在。';
    }

    // 如果产品是变体产品,获取变体信息
    $variation_fields = '';
    if ($product->is_type('variable')) {
        // 获取所有变体
        $available_variations = $product->get_available_variations();
        if (!empty($available_variations)) {
            $variation_fields .= '<select name="variation_id" id="variation_select_' . $product_id . '" style="display:none;">';
            $variation_fields .= '<option value="">' . __('Choose an option', 'woocommerce') . '</option>';
            foreach ($available_variations as $variation) {
                $variation_id = $variation['variation_id'];
                $variation_label = implode(' / ', $variation['attributes']);
                $variation_fields .= '<option value="' . $variation_id . '">' . $variation_label . '</option>';
            }
            $variation_fields .= '</select>';
        }
    }

    // 生成按钮HTML
    $button_html = sprintf(
    '<form class="add_to_cart_form" method="post" action="%s" id="add_to_cart_form_%d">
        <input type="hidden" name="action" value="add_to_cart_and_checkout" />
        <input type="hidden" name="product_id" value="%d" />
        <div class="button-wrapper">
            <button type="button" class="button initial-button" id="initial_button_%d" οnclick="showVariationSelector(%d)">%s</button>
            <button type="submit" class="button submit-button" id="submit_button_%d" style="display:none;">%s</button>
        </div>
        <div class="variation-selector-wrapper">%s</div>
    </form>',
    esc_url(admin_url('admin-post.php')),
    intval($product_id),
    intval($product_id),
    intval($product_id),
    intval($product_id),
    esc_html($button_label),
    intval($product_id),
    esc_html($button_label),
    $variation_fields
);

    return $button_html;
}

// 注册短代码
add_shortcode('add_to_cart_button', 'add_product_to_cart_button');

function handle_add_to_cart_and_checkout() {
    // 确保 WooCommerce 环境已加载
    if (!function_exists('wc')) {
        include_once ABSPATH . 'wp-content/plugins/woocommerce/includes/wc-core-functions.php';
    }

    // 初始化 WooCommerce 购物车
    if (function_exists('wc_load_cart')) {
        wc_load_cart();
    }

    // 获取产品ID和变体ID
    $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
    $variation_id = isset($_POST['variation_id']) ? intval($_POST['variation_id']) : 0;

    // 检查产品ID是否有效
    if ($product_id > 0 && WC()->cart) {
        // 获取购物车中的所有项目
        $cart = WC()->cart->get_cart();

        // 检查购物车中是否已有此产品
        $product_exists_in_cart = false;
        foreach ($cart as $cart_item_key => $cart_item) {
            if ($cart_item['product_id'] === $product_id && $cart_item['variation_id'] === $variation_id) {
                // 更新购物车中的产品数量
                WC()->cart->set_quantity($cart_item_key, $cart_item['quantity'] + 1);
                $product_exists_in_cart = true;
                break;
            }
        }

        // 如果购物车中没有此产品,则添加
        if (!$product_exists_in_cart) {
            WC()->cart->add_to_cart($product_id, 1, $variation_id);
        }

        // 跳转到结账页面
        wp_safe_redirect(wc_get_checkout_url());
        exit;
    } else {
        // 如果产品ID无效,返回错误信息
        wp_die('无效的产品ID。');
    }
}

// 注册处理表单提交的操作
add_action('admin_post_nopriv_add_to_cart_and_checkout', 'handle_add_to_cart_and_checkout');
add_action('admin_post_add_to_cart_and_checkout', 'handle_add_to_cart_and_checkout');

对应的js代码

document.addEventListener('DOMContentLoaded', function() {
    window.showVariationSelector = function(productId) {
        var variationSelector = document.getElementById('variation_select_' + productId);
        var initialButton = document.getElementById('initial_button_' + productId);
        var submitButton = document.getElementById('submit_button_' + productId);

        if (variationSelector) {
            variationSelector.style.display = 'block';
            initialButton.style.display = 'none';
            submitButton.style.display = 'inline-block';
        } else {
            // 如果没有变体选择器,直接提交表单
            document.getElementById('add_to_cart_form_' + productId).submit();
        }
    };
});

原文地址:https://blog.csdn.net/qq_45026664/article/details/139161326

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!