101 lines
3.1 KiB
PHP
101 lines
3.1 KiB
PHP
<?php
|
|
namespace Mirasco\Components\ShortCodes;
|
|
|
|
use Mirasco\Components\Products\ProductCategoryTaxonomy;
|
|
use Mirasco\Components\Products\ProductPostType;
|
|
|
|
class MirascoProductCategoryGridShortCode
|
|
{
|
|
const TAG = 'mirasco_product_category_grid';
|
|
|
|
public function __construct()
|
|
{
|
|
add_shortcode( static::TAG, [ $this, 'render_short_code' ] );
|
|
}
|
|
|
|
public function render_short_code( $atts )
|
|
{
|
|
$atts = wp_parse_args( $atts, [
|
|
'category' => 'beef'
|
|
]);
|
|
$taxonomy = ProductCategoryTaxonomy::getInstance()->getKey();
|
|
$the_term = get_term_by( 'slug', $atts['category'], $taxonomy );
|
|
$query = new \WP_Query([
|
|
'post_type' => ProductPostType::getInstance()->getKey(),
|
|
'posts_per_page' => -1,
|
|
'order' => 'ASC',
|
|
'tax_query' => [
|
|
[
|
|
'field' => 'slug',
|
|
'taxonomy' => $taxonomy,
|
|
'terms' => $atts['category'],
|
|
'orderby' => 'term_order'
|
|
]
|
|
]
|
|
]);
|
|
$posts = array_map( function( \WP_Post $post ) use ( $taxonomy ) {
|
|
// Get terms.
|
|
$post->terms = wp_get_object_terms( $post->ID, [
|
|
'taxonomy' => $taxonomy,
|
|
]);
|
|
// Get post thumbnail.
|
|
$thumb_id = get_post_thumbnail_id( $post->ID );
|
|
if ( ! empty( $thumb_id ) ) {
|
|
$url = wp_get_attachment_image_url( $thumb_id, 'large' );
|
|
} else {
|
|
$url = false;
|
|
}
|
|
$post->image = $url;
|
|
return $post;
|
|
}, $query->posts );
|
|
|
|
$terms = [];
|
|
|
|
// Extract post terms.
|
|
foreach( $posts as $post ) {
|
|
foreach ( $post->terms as $term ) {
|
|
if ( ! in_array( $term, $terms ) ) {
|
|
$terms[] = $term;
|
|
}
|
|
}
|
|
}
|
|
usort($terms ,'compareTermOrder');
|
|
echo "<script>
|
|
console.log('term list: '+" . json_encode($terms) . "')
|
|
</script>";
|
|
ob_start();
|
|
echo '<div class="product-category-grid">';
|
|
foreach( $terms as $term ){
|
|
if ( 0 == $term->parent || $the_term->term_id == $term->term_id ) {
|
|
continue;
|
|
}
|
|
echo '<div class="term-wrap">
|
|
<h3 class="cuts">'.$term->name.'</h3>';
|
|
foreach( $posts as $post ){
|
|
$terms = $post->terms;
|
|
$in_array = false;
|
|
foreach( $terms as $_term ) {
|
|
if ( $_term->term_id == $term->term_id ) {
|
|
$in_array = true;
|
|
}
|
|
}
|
|
if ( ! $in_array ) {
|
|
continue;
|
|
}
|
|
echo '<div class="post-item">';
|
|
if ( $post->image ) {
|
|
echo '<a href="' . $post->image . '" class="foobox" rel="foobox" data-width="400">
|
|
' . $post->post_title . '
|
|
<i class="fa fa-camera"></i>
|
|
</a>';
|
|
} else {
|
|
echo $post->post_title;
|
|
}
|
|
echo '</div>';
|
|
}
|
|
echo '</div>';
|
|
}
|
|
echo '</div>';
|
|
return ob_get_clean();
|
|
}
|
|
} |