Skip to content

Instantly share code, notes, and snippets.

@MortenAndersen
Forked from ChromeOrange/product-tag.php
Last active September 25, 2015 15:22
Show Gist options
  • Save MortenAndersen/2cda4918ef1b9db7f12e to your computer and use it in GitHub Desktop.
Save MortenAndersen/2cda4918ef1b9db7f12e to your computer and use it in GitHub Desktop.
WooCommerce : display products in a tag. Add to your theme functions.php file
/**
* List products in a product tag shortcode
* Useage : [product_tag tag="foo"]
*/
add_shortcode( 'product_tag', 'woocommerce_product_tag' );
function woocommerce_product_tag( $atts ){
global $woocommerce, $woocommerce_loop;
if ( empty( $atts ) ) return;
extract( shortcode_atts( array(
'per_page' => '4',
'columns' => '4',
'orderby' => 'rand',
'order' => 'desc',
'tag' => ''
), $atts ) );
if ( ! $tag ) return;
// Default ordering args
$ordering_args = $woocommerce->query->get_catalog_ordering_args( $orderby, $order );
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'orderby' => $ordering_args['orderby'],
'order' => $ordering_args['order'],
'posts_per_page' => $per_page,
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_tag',
'terms' => array( esc_attr($tag) ),
'field' => 'slug',
'operator' => 'IN'
)
)
);
if ( isset( $ordering_args['meta_key'] ) ) {
$args['meta_key'] = $ordering_args['meta_key'];
}
ob_start();
$products = new WP_Query( $args );
$woocommerce_loop['columns'] = $columns;
if ( $products->have_posts() ) : ?>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php woocommerce_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
wp_reset_postdata();
return '<div class="woocommerce">' . ob_get_clean() . '</div>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment