Reputation: 11
I Am using Add Text under Single Product Short Description in Woocommerce 2nd code snippet on this answer.
I Changed a bit the following:
function custom_single_excerpt(){
global $post, $product;
$short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt );
if ( ! $short_description )
return;
// The custom text
$custom_text = 'custom text goes in here, custom text goes in here, custom text goes in here, custom text goes in here';
?>
<div class="woocommerce-product-details__short-description">
<?php echo $short_description // WPCS: XSS ok. ?>
<div class="custom-text">
<?php echo $custom_text; // WPCS: XSS ok. ?>
</div>
</div>
<?php
}
I'd like to edit this to be able to just have it show on certain product categories if possible but not sure how.
Any advice gratefully received.
Upvotes: 0
Views: 2420
Reputation: 253784
You can use has_term()
WordPress conditional function to target specific product categories:
add_action( 'woocommerce_single_product_summary', 'custom_single_product_summary', 2 );
function custom_single_product_summary(){
global $product;
// Here set your product category terms Ids, slugs or names.
$categories = array( 'toons', 'dolls' );
if( has_term( $categories, 'product_cat', $product->get_id() ) ){
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 );
add_action( 'woocommerce_single_product_summary', 'custom_single_excerpt', 20 );
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
For multiple different texts by category, you will use instead:
add_action( 'woocommerce_single_product_summary', 'custom_single_product_summary', 2 );
function custom_single_product_summary(){
global $product;
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 );
add_action( 'woocommerce_single_product_summary', 'custom_single_excerpt', 20 );
}
function custom_single_excerpt(){
global $post, $product;
$short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt );
if ( ! $short_description )
return;
// For "toons" category
if ( has_term( array('toons'), 'product_cat', $product->get_id() ) ) {
$custom_text = __('A custom text for "Toons" category');
}
// For "people" category
elseif ( has_term( array('people'), 'product_cat', $product->get_id() ) ) {
$custom_text = __('A different custom text for "People" category');
}
// For All other categories (or no categories)
else {
$custom_text = __('A custom text for All other categories (or no categories)');
}
echo '<div class="woocommerce-product-details__short-description">' .
$short_description // WPCS: XSS ok.
. '<div class="custom-text">' . $custom_text // WPCS: XSS ok.
. '</div>
</div>';
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Upvotes: 3