Leslie Leslie - 1 year ago 75
PHP Question

Displaying a customized product SKU based on categories in shop and archives pages

I am mostly a designer and trying to wet my feet in PHP as it pertains to Wordpress.

I am using woocommerce and would like to display the SKU on the category pages. So far I have this:

//* add SKU to shop page

add_action( 'woocommerce_after_shop_loop_item_title', 'shop_sku' );
function shop_sku(){
global $product;
echo '<span itemprop="productID" class="sku">SKU: ' . $product->sku . '<br></span>';

Works great. However my client would like to display a letter before the SKU depending on the category. Rather than go through and change all the SKU numbers, I thought it might make sense to add to the function.

add_action( 'woocommerce_after_shop_loop_item_title', 'shop_sku' );
function shop_sku(){
global $product;
$product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );

if ($product_cats == "Contemporary Modern Area Rugs") {
echo '<span itemprop="productID" class="sku">SKU: C-' . $product->sku . '<br></span>';

elseif ($product_cats == "Traditional Oriental Area Rugs") {
echo '<span itemprop="productID" class="sku">SKU: T-' . $product->sku . '<br></span>';

else {
echo '<span itemprop="productID" class="sku">SKU: S-' . $product->sku . '<br></span>';

My problem is that only the third condition is met, meaning all the SKU numbers display with an "S-" in front.

Any hints?


Answer Source

Is better to use the native conditional function has_term() with the category slugs or IDs.

I have customized your code a little:

add_action( 'woocommerce_after_shop_loop_item_title', 'shop_sku' );
function shop_sku(){
    global $post, $product;

    //It's better to REPLACE the category name by the slug or the ID !!!

    if ( !has_term( 'Contemporary Modern Area Rugs', 'product_cat' ) && !has_term( 'Traditional Oriental Area Rugs', 'product_cat' ) )
        $letter = 'S';

    if ( has_term( 'Contemporary Modern Area Rugs', 'product_cat' ) )
        $letter = 'C';

    if ( has_term( 'Traditional Oriental Area Rugs', 'product_cat' ) )
        $letter = 'T';

    echo '<span itemprop="productID" class="sku">SKU: '. $letter .'-' . $product->sku . '<br></span>';

Naturally, this goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Reference: WordPress Function has_term()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download