Last active
August 8, 2019 16:28
-
-
Save Garconis/5b86671efdde4cc3157e74e0e2767eb3 to your computer and use it in GitHub Desktop.
WooCommerce | Create a shortcode for WooCommerce product links, which adds a class based on the if the product is out of stock or in stock.
This file contains 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
<?php | |
/* | |
Create a shortcode that will wrap content, and will return a product link | |
based on the product ID that is added to the shortcode | |
Usage: [stock_product_link id="123"]The text, image, etc. you want to link[/stock_product_link] | |
*/ | |
if( !function_exists('custom_shortcode_stock_product_link') ) { | |
function custom_shortcode_stock_product_link( $atts, $content = null ) { | |
// Shortcode Attributes | |
$atts = shortcode_atts( | |
array( | |
'id' => '', | |
), | |
$atts, 'stock_product_link' | |
); | |
$product_id = $atts['id']; | |
// Get an instance of the WC_Product object | |
$product = wc_get_product( $product_id ); | |
// Display custom class, based on if product is in or out of stock | |
$class = $product->is_in_stock() ? ' class="piece-in"' : ' class="piece-out"'; | |
// The product link | |
$product_link = $product->get_permalink(); | |
// The product add-to-cart link | |
$product_cart_link = $product->add_to_cart_url(); | |
// The output | |
return '<a xlink:href="'.$product_cart_link.'"'.$class.'>'.$content.'</a>'; | |
} | |
add_shortcode( 'stock_product_link', 'custom_shortcode_stock_product_link' ); | |
} | |
/* | |
Create a shortcode that will wrap content, and will return an element | |
with a specific class, based on if the product ID that is added to the shortcode is IN STOCK | |
Usage: [stock_product_piece id="123"]The text, image, etc. you want to link[/stock_product_piece] | |
*/ | |
if( !function_exists('custom_shortcode_stock_product_piece') ) { | |
function custom_shortcode_stock_product_piece( $atts, $content = null ) { | |
// Shortcode Attributes | |
$atts = shortcode_atts( | |
array( | |
'id' => '', | |
), | |
$atts, 'stock_product_piece' | |
); | |
$product_id = $atts['id']; | |
// Get an instance of the WC_Product object | |
$product = wc_get_product( $product_id ); | |
// Display custom class, based on if product is in or out of stock | |
if ( $product->is_in_stock() ) { | |
return $content; | |
} | |
else { | |
return; | |
} | |
} | |
add_shortcode( 'stock_product_piece', 'custom_shortcode_stock_product_piece' ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment