Skip to content

Instantly share code, notes, and snippets.

@JiveDig
Last active May 15, 2019 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JiveDig/6adde04666c189b6089fcfeca4988c47 to your computer and use it in GitHub Desktop.
Save JiveDig/6adde04666c189b6089fcfeca4988c47 to your computer and use it in GitHub Desktop.
Create a direct to cart/checkout/page add to cart button in 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 );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment