Created
November 1, 2012 09:32
-
-
Save ChromeOrange/3992721 to your computer and use it in GitHub Desktop.
Custom Shortcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_shortcode( 'custom-add-to-cart','custom_woocommerce_product_add_to_cart' ); | |
/** | |
* Display a single prodcut price + cart button | |
* | |
* @access public | |
* @param array $atts | |
* @return string | |
*/ | |
function custom_woocommerce_product_add_to_cart( $atts ) { | |
if (empty($atts)) return; | |
global $wpdb, $woocommerce; | |
if (!isset($atts['style'])) $atts['style'] = 'border:4px solid #ccc; padding: 12px;'; | |
if ($atts['id']) : | |
$product_data = get_post( $atts['id'] ); | |
elseif ($atts['sku']) : | |
$product_id = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $atts['sku'])); | |
$product_data = get_post( $product_id ); | |
else : | |
return; | |
endif; | |
if ($product_data->post_type=='product') { | |
$product = $woocommerce->setup_product_data( $product_data ); | |
ob_start(); | |
?> | |
<p class="product"> | |
<?php echo $product->get_price_html(); ?> | |
<?php woocommerce_template_single_add_to_cart(); ?> | |
</p> | |
<?php | |
return ob_get_clean(); | |
} elseif ($product_data->post_type=='product_variation') { | |
$product = new WC_Product( $product_data->post_parent ); | |
$GLOBALS['product'] = $product; | |
$variation = new WC_Product_Variation( $product_data->ID ); | |
ob_start(); | |
?> | |
<p class="product product-variation" style="<?php echo $atts['style']; ?>"> | |
<?php echo $product->get_price_html(); ?> | |
<?php | |
$link = $product->add_to_cart_url(); | |
$label = apply_filters('add_to_cart_text', __('Add to cart', 'woocommerce')); | |
$link = add_query_arg( 'variation_id', $variation->variation_id, $link ); | |
foreach ($variation->variation_data as $key => $data) { | |
if ($data) $link = add_query_arg( $key, $data, $link ); | |
} | |
printf('<a href="%s" rel="nofollow" data-product_id="%s" class="button add_to_cart_button product_type_%s">%s</a>', esc_url( $link ), $product->id, $product->product_type, $label); | |
?> | |
</p><?php | |
return ob_get_clean(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment