为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
哔哔one 2022-06-11 18:13:11
我正在尝试为特定 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))”有什么好处吗?
查看完整描述

2 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

要在此特定类别的产品页面中显示文本,您应该添加条件标签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


查看完整回答
反对 回复 2022-06-11
?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

这有效:


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';

}


}


查看完整回答
反对 回复 2022-06-11
  • 2 回答
  • 0 关注
  • 143 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号