Last active
December 15, 2015 15:18
-
-
Save ChromeOrange/5280285 to your computer and use it in GitHub Desktop.
WooCommerce : display products in a tag. Add to your theme functions.php file
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
/** | |
* 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' => '12', | |
'columns' => '4', | |
'orderby' => 'title', | |
'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