Skip to content

Instantly share code, notes, and snippets.

@BruceMcKinnon
Created August 2, 2021 23:41
Show Gist options
  • Save BruceMcKinnon/dead0533f8eb08339890423cd9a89f66 to your computer and use it in GitHub Desktop.
Save BruceMcKinnon/dead0533f8eb08339890423cd9a89f66 to your computer and use it in GitHub Desktop.
Woo Custom Product Add to Cart and Checkout
//
// Shortcode to add a custom Add-To-Cart and Checkout button
//
// Button displays icon, price and product name
//
function bl_add_to_cart_button( $atts ) {
$params = shortcode_atts( array(
'id' => null,
'text' => '{product_name}',
'show_icon' => 1,
'show_price' => 1,
'class' => 'button add_to_cart',
'icon_class' => 'fas fa-cart-plus',
), $atts );
$html = '<a class="'.$params['class'].'" ';
if ( intval( $params['id'] ) > 0 && function_exists( 'wc_get_product' ) ) {
$_product = wc_get_product( $params['id'] );
$title = $params['text'];
$link_url = ' href="'.get_bloginfo('url').'/checkout/?add-to-cart='.$params['id'].'" ';
if ( $params['show_price'] > 0 ) {
$price = wc_price( $_product->get_price() );
$title = '<span class="price">'.$price . '</span>' . $title;
}
if ( stripos($title,'{product_name}') !== false ) {
$prod_name = $_product->get_title();
$title = str_ireplace( '{product_name}', $prod_name, $title );
}
if ( strlen($params['icon_class']) > 0 ) {
$icon = '<i class="'.$params['icon_class'].'"></i>';
}
$html .= $link_url.'>'.$icon.$title;
} else {
$html .= '>';
}
return $html.'</a>';
}
add_shortcode( 'bl-add-to-cart', 'bl_add_to_cart_button' );
// e.g., [bl-add-to-cart class="button add_to_cart bottom-15" id=518]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment