WooCommerce, WordPress

Handy helper function for product listing page in WooCommerce

WooCommerce is a free e-commerce plugin for WordPress. It is designed for small to large-sized organization to sell the good and services online. I am not going to explain everything about WooCommerce here but  list few helper function that makes developer job easier when developing the WooCommerce sites. One, with the basic knowledge of WooCommerce will understand and find the following functions handy.

  1. Function to list the attributes related to the current category product in the archive-product page/product listing page/product
function getProductCurrentCatAttributes($catSlug){
    $query_args = [
        'status' => 'publish',
        'limit' => -1,
        'category' => [$catSlug],
    ];
    $products = wc_get_products($query_args);
    $data = [];
    foreach ($products as $product) {
        $attributeTax = $product->get_attributes();
        if ($attributeTax) {
            foreach ($attributeTax as $taxonomy => $attribute) {
                foreach ($attribute->get_terms() as $term) {
                    $data[$taxonomy][$term->term_id] = $term->slug;
                }
            }
        }
    }
    return $data;
}

Get the current category Slug in archive-product.php page :

$category_slug = get_queried_object();
$catSlug = $category_slug->slug;

2. Function to count the number of product related to particular category and related attribute terms .

function getAttrProductCount($productCat,$attrName,$attrTerm){
    $args = [
        'post_type' => 'product',
        'tax_query' => [
            'relation' => 'AND',
              [
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => [$productCat],
            ],
            [
                'taxonomy' => $attrName,
                'field'    => 'slug',
                'terms'    => [$attrTerm],
            ],
        ],
    ];
    $query = new WP_Query( $args );
    return $query->found_posts;
}

3. Use the aforementioned function in archive-product.php to get the list the attribute and it’s terms related to current category products. I have used form and checkbox, so that I could filter the products based on current category and selected attribute term.   Also, I find symphony HttpFoundation Component handy to get\request the selected attribute terms

 <?php  use Symfony\Component\HttpFoundation\Request; ?>
<form class="woocommerce-attribute" method="get">
	<?php
	$attributes = getProductCurrentCatAttrib($catSlug);
	if($attributes) {
		foreach ($attributes as $attrName => $attrArray) {
			$attrNameArray = explode('pa_',$attrName);
			$taxName = $attrNameArray[1];
			$taxLabel = wc_attribute_label($attrName); // Attribute name
			?>
		<div class="filter-panel <?=$class?>">
			<div class="filter-title" type="button"><?=$taxLabel?></div>
			<div class="filter-panel-body pb-0">
				<div class="custom-field-wrap">

		<?php $currentTaxonomy = (new Request($_GET))->get($taxName, []); 
		foreach ($attrArray as $attrID => $attrSlug) {
			$term_obj = get_term_by('slug', $attrSlug, $attrName);
			$termLabel = $term_obj->name;
			$termID = $attrID;
			$termSlug = $attrSlug;
			$selected = "";
			if(in_array($attrSlug, $currentTaxonomy)){
				$selected = 'checked="checked"';
			}
			$productFound = getAttrProductCount($catSlug,$attrName,$termSlug);

			?>
			<div class="custom-field">
				<input type="checkbox" name="<?=$taxName?>[]" 
				class="custom-field__control js-attr-filters"
			   id="<?=$termSlug?>-<?=$termID?>" value="<?=$termSlug?>" <?=$selected?> />
				<label for="<?=$termSlug?>-<?=$termID?>"><?=$termLabel?> 
				<span class="cat-count"><?php echo '('.$productFound.')'; ?></span></label>
			</div>

		<?php
		} ?>

				</div>
			</div>
		</div>
	<?php
		}
	}
	?>

	</form>

4. Get the list of all the attribute terms

<?php use Symfony\Component\HttpFoundation\Request; ?>
<form class="woocommerce-attribute" method="get">
<?php
$getTaxKey="";
$getTaxTermValue ="";
$attribute_taxonomies = wc_get_attribute_taxonomies();
if($attribute_taxonomies) {
$count = count($attribute_taxonomies);
foreach ($attribute_taxonomies as $attrTax){
$taxName = $attrTax->attribute_name;
$taxLabel = $attrTax->attribute_label;
?>
<div class="filter-panel <?=$class?>">
	<div class="filter-title" type="button"><?=$taxLabel?></div>
		<div class="filter-panel-body pb-0">
			<div class="custom-field-wrap">
			<?php
			$currentTaxonomy = (new Request($_GET))->get($taxName, []);
			$terms = get_terms('pa_'.$taxName, [
				'hide_empty' => false,
			]);
			foreach ($terms as $term) {
				$selected = "";
				if(in_array($term->slug, $currentTaxonomy)){
					$selected = 'checked="checked"';
				}
				?>
				<div class="custom-field">
					<input type="checkbox" name="<?=$taxName?>[]" class="custom-field__control js-attr-filters"
						   id="<?=$term->slug?>-<?=$term->term_id?>" value="<?=$term->slug?>" <?=$selected?> />
					<label for="<?=$term->slug?>-<?=$term->term_id?>"><?=$term->name?> <span
							class="cat-count"><?php echo '('.$term->count.')'; ?></span></label>
				</div>
			<?php
			} ?>
			</div>
	</div>
</div>
<?php
	}
}
?>
</form>

5. Don’t forget to submit the form on selecting the attribute terms.

$( '.woocommerce-attribute' ).on( 'change', '.js-attr-filters', function() {
	$( this ).closest( 'form' ).submit();
});

 

 

 

 

 

Views: 61

Standard