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

我正在尝试为特定 woo 商务类别中的产品显示自定义文本。这是我添加到 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))”有什么好处吗?



哔哔one
浏览 145回答 2
2回答

慕森王

要在此特定类别的产品页面中显示文本,您应该添加条件标签is_product()并使用如下功能检查它是否具有正确的类别has_term():add_action( 'woocommerce_after_main_content', 'add_my_text' );function add_my_text() {&nbsp; &nbsp; //1st grab the product/post object for the current page if you don't already have it:&nbsp; &nbsp; global $post;&nbsp; &nbsp; //2nd you can get the product category term objects (the categories) for the product&nbsp; &nbsp; $terms = wp_get_post_terms( $post->ID, 'product_cat' );&nbsp; &nbsp; foreach ( $terms as $term ) $categories[] = $term->slug;&nbsp; &nbsp; //Then we just have to check whether a category is in the list:&nbsp; &nbsp; if ( is_product_category( 'category1' ) || is_product() && in_array( 'category1', $categories ) ) {&nbsp; &nbsp; &nbsp; &nbsp; echo '<p>This is my extra text.</p>';&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;}对于这个if (function_exists(...问题,这是一个向后兼容性的问题,正如这个答案中提到的:https ://wordpress.stackexchange.com/a/111318/136456

呼啦一阵风

这有效: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';}}
打开App,查看更多内容
随时随地看视频慕课网APP