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>
CodePudding user response:
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 >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