php 在WooCommerce中创建直接购物车/结帐/页面添加到购物车按钮。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 在WooCommerce中创建直接购物车/结帐/页面添加到购物车按钮。相关的知识,希望对你有一定的参考价值。

<?php

/**
 * Create a direct to cart/checkout/page add to cart button.
 *
 * Example: [buy_now id="1234" redirect="checkout"]
 *
 * @version  1.0.0
 * @author   @JiveDig
 * @link     https://gist.github.com/JiveDig/6adde04666c189b6089fcfeca4988c47
 * @uses     WooCommerce
 *
 * @return   string|HTML
 */
add_shortcode( 'buy_now', function( $atts ) {

	// Bail if no Woo.
	if ( ! class_exists( 'WooCommerce' ) ) {
		return '';
	}

	// Shortcode attributes.
	$atts = shortcode_atts( array(
		'id'         => '',       // product id to automatically add to cart.
		'class'      => 'button', // html class(es), comma-separated.
		'redirect'   => 'cart',   // slug, path, or page/post ID to go to. If empty, will use current page.
		'text'       => __( 'Buy Now', 'textdomain' ),
		'show_price' => true,     // true/false, to show the product price.
	), $atts, 'buy_now' );

	// Bail if no ID.
	if ( ! $atts['id'] ) {
		return '';
	}

	// Get product.
	$product = wc_get_product( $atts['id'] );

	// Bail if no product.
	if ( ! $product ) {
		return '';
	}

	// Sanitize attributes.
	$atts = array(
		'id'         => $product->get_id(),
		'class'      => sanitize_text_field( $atts['class'] ),
		'redirect'   => sanitize_key( $atts['redirect'] ),
		'text'       => esc_html( $atts['text'] ),
		'show_price' => filter_var( $atts['show_price'], FILTER_VALIDATE_BOOLEAN ),
	);

	$url = '';

	// If we have a redirect.
	if ( $atts['redirect'] ) {
		// If it's a page ID.
		if ( is_numeric( $atts['redirect'] ) ) {
			$url = get_permalink( $atts['redirect'] );
		}
		// Must be a string.
		else {
			// Maybe get the page.
			if ( $page = get_page_by_path( $atts['redirect'] ) ) {
				$url = get_permalink( $page->ID );
			}
		}
	}
	// No redirect.
	else {
		// Get the current page/post ID.
		$url = get_permalink( get_the_ID() );
	}

	// Bail if no URL.
	if ( ! $url ) {
		return '';
	}

	// Build add to cart URL.
	$url = add_query_arg( 'add-to-cart', $atts['id'], $url );

	// Build the class.
	$class = $atts['class'] ? sprintf( ' class="%s"', $atts['class'] ) : '';

	// Build the text.
	$text = $atts['text'];
	
	// Maybe add the price.
	if ( $atts['show_price'] ) {
		$text .= sprintf( '&nbsp;&ndash;&nbsp;%s', $product->get_price_html() );
	}

	// Return the link.
	return sprintf( '<p><a href="%s"%s>%s</a></p>', $url, $class, $text );
});

以上是关于php 在WooCommerce中创建直接购物车/结帐/页面添加到购物车按钮。的主要内容,如果未能解决你的问题,请参考以下文章

使用会话变量在 PHP 中创建一个简单的购物篮

Woocommerce 添加到自定义产品的购物车按钮

php WooCommerce:在购物车页面上添加继续购物按钮

php WOOCOMMERCE在购物车中重新加载商品数量

php [WooCommerce预订]在购物车预订到期时修改

小计购物车变量 php WooCommerce