-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducts._by_taxonomy.php
105 lines (83 loc) · 2.67 KB
/
products._by_taxonomy.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
add_shortcode('product_by_taxonomy','cnmd_get_products_by_taxonomy');
/**
* Shortcode to list all (or limited) products by taxonomy
*
* Based on [product_categories] in class-wc-shortcodes.php
*/
function cnmd_get_products_by_taxonomy( $atts ) {
global $woocommerce_loop;
/**
* number How many to show
* orderby What to orderby
* order ASC or DESC
* columns The columns of the grid to display
* hide_empty Hide terms with no assigned products
* parent Set the parent parameter to 0 to only display top level categories.
* ids Set IDs to a comma separated list of category IDs to only show those.
* taxonomy the taxonomy to show
*/
$atts = shortcode_atts( array(
'number' => null,
'orderby' => 'name',
'order' => 'ASC',
'columns' => '4',
'hide_empty' => 1,
'parent' => '',
'ids' => '',
'taxonomy' => 'product_cat',
), $atts, 'product_by_taxonomy' );
$ids = array_filter( array_map( 'trim', explode( ',', $atts['ids'] ) ) );
$hide_empty = ( true === $atts['hide_empty'] || 'true' === $atts['hide_empty'] || 1 === $atts['hide_empty'] || '1' === $atts['hide_empty'] ) ? 1 : 0;
// Ensure we're after a valid taxonomy
$public_builtin_taxonomies = get_taxonomies( array(
'public' => true,
'_builtin' => true,
));
$public_custom_taxonomies = get_taxonomies( array(
'public' => true,
'_builtin' => false,
));
$all_taxonomies = array_merge( $public_builtin_taxonomies, $public_custom_taxonomies);
if (! in_array($atts['taxonomy'], $all_taxonomies)) {
return;
}
// get terms and workaround WP bug with parents/pad counts
$args = array(
'orderby' => $atts['orderby'],
'order' => $atts['order'],
'hide_empty' => $hide_empty,
'include' => $ids,
'pad_counts' => true,
'child_of' => $atts['parent'],
'taxonomy' => $atts['taxonomy'],
);
$terms = get_terms( $args );
if ( '' !== $atts['parent'] ) {
$terms = wp_list_filter( $terms, array( 'parent' => $atts['parent'] ) );
}
if ( $hide_empty ) {
foreach ( $terms as $key => $term ) {
if ( 0 == $term->count ) {
unset( $terms[ $key ] );
}
}
}
if ( $atts['number'] ) {
$terms = array_slice( $terms, 0, $atts['number'] );
}
$columns = absint( $atts['columns'] );
$woocommerce_loop['columns'] = $columns;
ob_start();
if ( $terms ) {
woocommerce_product_loop_start();
foreach ( $terms as $term ) {
wc_get_template( 'content-product_cat.php', array(
'category' => $term,
) );
}
woocommerce_product_loop_end();
}
woocommerce_reset_loop();
return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';
}