Skip to content

Instantly share code, notes, and snippets.

@WillBrubaker
Created August 6, 2014 15:33
Show Gist options
  • Save WillBrubaker/630a844d0d5b7aca7195 to your computer and use it in GitHub Desktop.
Save WillBrubaker/630a844d0d5b7aca7195 to your computer and use it in GitHub Desktop.
A snippet of code demonstrating how to create a shortcode that will output a number of items sold - This is specific to woocommerce
<?php
/* Do not copy the opening <?php tag above */
//Add the shortcode tag with its callback function:
add_shortcode( 'display_tickets_sold', 'wwm_display_tickets_sold' );
/**
* Given a valid product id, Outputs a number of 'units sold'
* Usage [display_tickets_sold product_id="####"] where #### is a valid product id.
* @param array $atts an array of shortcode attributes
* @return void|string returns a formatted html string indicating the number of units sold if the product_id
* is set and the meta key exists and the meta value is not empty. Otherwise, returns void
*/
function wwm_display_tickets_sold( $atts ) {
if ( ! isset( $atts['product_id'] ) ) {
return;
}
$product_id = absint( $atts['product_id'] );
$units_sold = get_post_meta( $product_id, 'total_sales', true );
if ( ! empty( $units_sole ) ) {
return '<p>' . sprintf( 'Units Sold: %s', $units_sold ) . '</p>';
}
return;
}
//You may not need the next line of code:
add_filter( 'widget_text', 'do_shortcode' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment