Skip to content

Instantly share code, notes, and snippets.

@0x7466
Last active December 15, 2020 07:56
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 0x7466/2ae6627cc8e8f2fdcf4ce9253aca851e to your computer and use it in GitHub Desktop.
Save 0x7466/2ae6627cc8e8f2fdcf4ce9253aca851e to your computer and use it in GitHub Desktop.
TFM Woocommerce Shortcodes
<?php
/**
* @link https://tfm.agency
* @since 1.0.0
* @package TFM WooCommerce Shortcodes
*
* @wordpress-plugin
* Plugin Name: TFM WooCommerce Shortcodes
* Plugin URI: https://tfm.agency
* Description: Bunch of needed shortcodes for WooCommerce.
* Version: 1.0.0
* Author: TFM Agency GmbH
* Author URI: https://tfm.agency
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Text Domain: tfm-woocommerce-shortcodes
*/
/**
* Attributes shortcode callback.
*/
function tfm_attributes_shortcode( $atts ) {
global $product;
if( ! is_object( $product ) || ! $product->has_attributes() ){
return;
}
// parse the shortcode attributes
$args = shortcode_atts( array(
'attributes' => array_keys( $product->get_attributes() ), // by default show all attributes
), $atts );
// is pass an attributes param, turn into array
if( is_string( $args['attributes'] ) ){
$args['attributes'] = array_map( 'trim', explode( '|' , $args['attributes'] ) );
}
// start with a null string because shortcodes need to return not echo a value
$html = '';
if( ! empty( $args['attributes'] ) ){
foreach ( $args['attributes'] as $attribute ) {
// get the WC-standard attribute taxonomy name
$taxonomy = strpos( $attribute, 'pa_' ) === false ? wc_attribute_taxonomy_name( $attribute ) : $attribute;
if( taxonomy_is_product_attribute( $taxonomy ) ){
// Get the attribute label.
$attribute_label = wc_attribute_label( $taxonomy );
// Build the html string with the label followed by a clickable list of terms.
// Updated for WC3.0 to use getters instead of directly accessing property.
$html .= get_the_term_list( $product->get_id(), $taxonomy, '<li class="bullet-arrow">' . $attribute_label . ': ' , ', ', '</li>' );
}
}
// if we have anything to display, wrap it in a <ul> for proper markup
// OR: delete these lines if you only wish to return the <li> elements
if( $html ){
$html = '<ul class="product-attributes">' . $html . '</ul>';
}
}
return $html;
}
add_shortcode( 'display_attributes', 'tfm_attributes_shortcode' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment