显示具有特定woo Commerce类别的产品的自定义文本

我正在尝试显示特定woo Commerce类别中产品的自定义文本。这是我添加到function.php的代码, 但它在类别页面而非产品页面中显示了文本。

add_action( 'woocommerce_after_main_content', 'add_my_text' ); function add_my_text() { if ( is_product_category( 'category1' ) ) { echo '< p> This is my extra text.< /p> '; } }

ps。在开头添加” if(function_exists(add_action))” 有什么好处?
#1要在此特定类别的” 产品” 页面上显示文本, 你应添加条件标签is_product()并使用has_term()函数检查其是否具有正确的类别, 如下所示:
add_action( 'woocommerce_after_main_content', 'add_my_text' ); function add_my_text() { //1st grab the product/post object for the current page if you don't already have it: global $post; //2nd you can get the product category term objects (the categories) for the product $terms = wp_get_post_terms( $post-> ID, 'product_cat' ); foreach ( $terms as $term ) $categories[] = $term-> slug; //Then we just have to check whether a category is in the list: if ( is_product_category( 'category1' ) || is_product() & & in_array( 'category1', $categories ) ) { echo '< p> This is my extra text.< /p> '; } }

对于if(function_exists(… 问题, 这是出于向后兼容性的问题, 如此答案中所述:https://wordpress.stackexchange.com/a/111318/136456
#2【显示具有特定woo Commerce类别的产品的自定义文本】这有效:
add_action( 'woocommerce_after_single_product_summary', 'add_text' ); function add_text() {if ( has_term( 'nail', 'product_cat' ) ) { echo 'Something'; } elseif ( has_term( 'tables', 'product_cat' ) ) { echo 'Something else'; }}

    推荐阅读