【发布时间】:2019-08-14 00:29:48
【问题描述】:
我想根据产品类别(或其他一些逻辑)自定义购物车和结帐订单汇总表中的文本。例如,对于“总计”文本(参见图片) - 如果购物车包含名为“杂货”的类别中的产品,那么我希望订单摘要中的文本显示为“总计估计”文本(参见图片以下)。如果购物车不包含任何杂货,那么我想要默认文本。
我找到了一个让我开始的解决方案,但需要更多帮助。
根据link,我将文件从 woocommerce/templates/ 复制到我的子主题中,并将其命名为 woocommerce/。例如,从review_order.php 文件中,我需要编辑下面的部分。
<th><?php _e( 'Total', 'woocommerce' ); ?></th>
但是,我不能只用硬编码字符串替换它,因为我的文本取决于逻辑。所以,我需要用函数替换字符串。
我想在下面做这样的事情:
<th><?php _e( get_my_custom_text(), 'woocommerce' ); ?></th>
,其中get_my_custom_text() 根据某些逻辑返回适当的文本,例如购物车中的物品类别。
- 我需要将包含函数
get_my_custom_text()的文件放在哪里,以便review_order.php可以看到该函数? - 这是实现我的目标的最佳方式吗?
更新:
在下面的讨论之后,我将添加我的 get_custom_text() 代码。我试图通过两种方式解决这个问题:第一种是woocommerce files 方式,第二种是下面建议使用add_filter( 'gettext', 'my_text_strings', 20, 3 ) 钩子。在这两种情况下,get_my_custom_text() 在检查购物车时似乎都不起作用。请参阅下面使用钩子方法的代码。我在 get_cart_contents_count() 上得到了一个错误,并且还得到了白屏死机
[23-Mar-2019 11:14:13 UTC] PHP Fatal error: Uncaught Error: Call to a member function get_cart_contents_count() on null in /opt/wordpress/htdocs/wp-content/themes/divi-child/functions.php:446
还得到:
[23-Mar-2019 11:16:05 UTC] PHP Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 20480 bytes) in /opt/wordpress/htdocs/wp-includes/class-wp-hook.php on line 279
add_filter( 'gettext', 'my_text_strings', 20, 3 );
function my_text_strings( $translated_text, $text, $domain ) {
switch ( $translated_text ) {
case 'Total' :
$translated_text = __( get_my_custom_text(), 'woocommerce' );
break;
}
return $translated_text;
}
function get_my_custom_text()
{
$is_groceries = has_groceries();
if($is_groceries){
return 'Total Estimate';
}else{
return 'Total';
}
}
//checks whether cart has any items in the "groceries" category
function has_groceries()
{
if( !$cart = WC()->cart ){
return false;
}
//not sure how error gets here if cart is null
write_log('cart contents: '. WC()->cart->get_cart_contents_count());
$categories = array(
'181' => 'groceries'
);
foreach( $cart->get_cart() as $cart_item ){
foreach ($categories as $category => $value) {
if( has_term( $category, 'product_cat', $cart_item['product_id']) ){
return true;
}
}
}
return false;
}
【问题讨论】:
-
实际上,我最初的问题是,如果我要使用复制 woocommerce 文件的方法,我将放置 get_my_custom_text() 的位置。但随着讨论的继续,需要更新问题
标签: php wordpress woocommerce