PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, January 18, 2022

[FIXED] Show label with term when product is featured in WooCommerce

 January 18, 2022     advanced-custom-fields, php, product, woocommerce, wordpress     No comments   

Issue

On WooCommerce single product page, using true/false via a advanced custom field, I have a label which is displays 'Featured' term in text and works fine.

This...

add_action( 'woocommerce_before_single_product_summary', 'property_main_details_field', 1 ); 
function property_main_details_field() {
    if ( get_field('featured_property') == 1 ) {
        ?>
        <span class="property-contract-badge">Featured</span>
        <?php 
    }
}

However, considering WooCommerce already has a Featured product selection built in, I would like to minimize and replace the custom field with the true/false ID from WooCommerce instead.

If I read correctly, featured products are now handled by product_visibility custom taxonomy for the term featured in WooCommerce.

If so, could I use Tax Query and then echo $term->name; in the span tag?

<span class="property-badge">
<?php   
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field'    => 'name',
'terms'    => 'featured',
'operator' => 'IN', 
);
?>
</span>

Solution

There are several options. 1 of them is to use wc_get_featured_product_ids(), that returns an array containing the IDs of the featured products.

If the productID then exists in the array, then it is a featured product.

function action_woocommerce_before_single_product_summary() {
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get productID
        $product_id = $product->get_id();
        
        // Returns an array containing the IDs of the featured products.
        $featured_product_ids = wc_get_featured_product_ids();
        
        // Checks if a value exists in an array
        if ( in_array( $product_id, $featured_product_ids ) ) {
            echo '<span class="property-contract-badge">Featured</span>';
        } else {
            echo 'NOT featured';
        }
    }
}
add_action( 'woocommerce_before_single_product_summary', 'action_woocommerce_before_single_product_summary', 1 );

Code goes in functions.php file of the active child theme (or active theme). Tested and works in Wordpress 5.8.1 & WooCommerce 5.8.0



Answered By - 7uc1f3r
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing