给WooCommerce的运费(Shipping Method)增加自定义描述字段

本站所有文章均为博主人工写作,绝无AI辅助成分,请放心参阅。

如果一个WooCommerce网站存在多种不同的运费(Shipping Method),则可能有必要让用户在运费选择的模块中了解不同运费的区别。你可以解释运输的时长,或者解释价格的构成等,总之就是提供更多信息帮助用户做出最好的选择。比如在这里,我就对每个运费添加了时长的解释:

一个便捷的办法是通过以下代码实现的:

add_filter('woocommerce_cart_shipping_method_full_label', 'brain1981_custom_shipping_method_label', 10, 2);
function brain1981_custom_shipping_method_label( $label, $method ){
	$txt = "";
	if( $method->id=="flat_rate:1" || $method->id=="free_shipping:4" ){
		$txt = 'In 15 Business days';
	}else if( $method->id=="flat_rate:2" || $method->id=="free_shipping:3" ){
		$txt = '7-10 Business days';
	}
	return $label . '<br /><small>' . $txt . '</small>';
}

需注意的是,WooCommerce的运费ID的格式都是以这样的形式呈现的:
flat_rate:1
free_shipping:2

以上这段代码就是事先辨认出这些运费ID,通过woocommerce_cart_shipping_method_full_label这个钩子在运费的标题后面增加一小段描述。如果你的运费数量不多且比较固定,这段代码就足够用了。

那么如果一个网站有很多种运费,并且经常会修改运费种类,上面这种hard codding的写法就会变得很臃肿且不易维护了。我们就需要给每个运费添加一个自定义的描述字段,实现后台管理描述,方便运维人员自己去修改运费设置。

首先实现给后台添加自定义字段:

/* Author: Brain - blog.brain1981.com */
add_action( 'woocommerce_init', 'brain1981_shipping_instance_form_fields_filters' );
function brain1981_shipping_instance_form_add_extra_fields( $settings ) {
	$settings['shipping_extra_field_description'] = array(
		'title'       => esc_html__( 'Description', 'woocommerce' ),
		'type'        => 'textarea',
		'placeholder' => esc_html__( 'Your shipping method description', 'woocommerce' ),
		'description' => '',
	);
	return $settings;
}
function brain1981_shipping_instance_form_fields_filters() {
	$shipping_methods = WC()->shipping->get_shipping_methods();
	foreach ( $shipping_methods as $shipping_method ) {
		add_filter( 'woocommerce_shipping_instance_form_fields_' . $shipping_method->id, 'brain1981_shipping_instance_form_add_extra_fields' );
	}
}

以上代码实现了这样的功能:

接下来是在开头第一张图的位置,调用出这个字段的内容:

/* Author: Brain - blog.brain1981.com */
add_filter('woocommerce_cart_shipping_method_full_label', 'brain1981_custom_shipping_method_label', 10, 2);
function brain1981_custom_shipping_method_label( $label, $method ){
	$rate_id = $method->id; // The Method rate ID (Method Id + ':' + Instance ID)
	$rate_id = str_replace(':', '_', $rate_id);
	$txt = get_option('woocommerce_'.$rate_id.'_settings')['shipping_extra_field_description'];
	return $label . '<br /><small>' . $txt . '</small>';
}

从以上代码中可以看出,WooCommerce的Shipping Method并不是像自定义文章类型那样的存储方式,而是存储于option表的,其键名是这种形式:
woocommerce_flat_rate_1_settings //对应flat_rate:1
woocommerce_free_shipping_2_settings //对应free_shipping:2

键值是一串JSON字符串,自定义字段就存于其中。知道了这个规律,就可以通过get_option方法把刚添加的字段调出来了。

本站所有文章均为原创,欢迎转载,请注明文章出处:https://blog.brain1981.com/2799.html。百度和各类采集站皆不可信,搜索请谨慎鉴别。技术类文章一般都有时效性,本人习惯不定期对自己的博文进行修正和更新,因此请访问出处以查看本文的最新版本。

关注我们的微信公众号-JennyStudio 本站记录了近几年的工作中遇到的一些技术问题和解决过程,“作品集”还收录了本人的大部分作品展示。除了本博客外,我们的工作室网站 – JennyStudio,内有更多作品回顾和展示。
您也可以扫描左边的二维码,关注我们的微信公众号,在微信上查看我们的案例。

2 关于 “给WooCommerce的运费(Shipping Method)增加自定义描述字段” 的评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注