php - WooCommerce 添加到购物车按钮后如何添加可自定义的文本
问题描述
我需要在 WooCommerce 中的添加到购物车按钮之后添加自定义文本元素。
我尝试使用我插入的这段代码functions.php
add_action( 'woocommerce_after_add_to_cart_button', 'inserisce_testo_dopobottone' );
function inserisce_testo_dopobottone() {
echo '<div class="second_content">New text</div>';
}
这是可行的,但现在我需要为每个页面定制文本。那可能吗?
解决方案
您可以通过woocommerce_product_options_general_product_data
操作挂钩添加自定义字段,这将向产品数据元框的常规选项卡添加一个新字段
基于此,您可以为每个产品显示不同的消息,或默认消息
所以你得到:
// Add to general_product_data tab
function action_woocommerce_product_options_general_product_data() {
// Text field
woocommerce_wp_text_input( array(
'id' => '_my_custom_text',
'label' => __( 'My custom text', 'woocommerce' ),
'placeholder' => '',
'description' => __( 'Add your custom text', 'woocommerce' ),
'desc_tip' => true,
));
}
add_action( 'woocommerce_product_options_general_product_data', 'action_woocommerce_product_options_general_product_data', 10, 0 );
// Save custom field
function action_woocommerce_admin_process_product_object( $product ) {
// Isset
if ( isset( $_POST['_my_custom_text'] ) ) {
// Update
$product->update_meta_data( '_my_custom_text', sanitize_text_field( $_POST['_my_custom_text'] ) );
}
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 );
// Display after add to cart button
function action_woocommerce_after_add_to_cart_button() {
global $product;
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Get meta
$message = $product->get_meta( '_my_custom_text' );
// When Empty, use default message
if ( empty ( $message ) ) {
$message = __( 'Default text', 'woocommerce' );
}
echo '<div class="second_content">' . $message . '</div>';
}
}
add_action( 'woocommerce_after_add_to_cart_button', 'action_woocommerce_after_add_to_cart_button' );
推荐阅读
- javascript - moment.js - 两个日期之间的差异已关闭
- graphql - 拉取对象数组时出现 nuxt-apollo 问题
- node.js - 调整图像节点大小 js-Imagemagick
- html - 标签中允许的内容
- c++ - 滤除峰值距离测量
- java - 如何让您的应用显示对话框(AndroidStudio)?
- java - Java 应用程序在 Netbeans 中将其构建为 .jar 后无法找到文件?
- sql - 注册的类似表将天分成行,将它们格式化为列
- python - Spark XML - 使用 Excel 中的 XML
- c# - 在 WPF 中编辑名称后,ComboBox Selected Item 正在工作