php - 在每个产品 ID/WP 的 WooCommerce 产品价格后添加文本

标签 php wordpress woocommerce

我的子主题的functions.php 文件中有以下代码,并且效果很好。

function themeprefix_custom_price_message( $price ) { 

global $post;

$product_id = $post->ID;
$my_product_array = array( 270,373,378,506,1306,1311,1312,1444,1445,1447,1449,1930,1932,1933,1934,1935,1963,4146,4152,4153,4154 );//add in product IDs
if ( in_array( $product_id, $my_product_array )) {
    $textafter = ' Each/Min 12'; //add your text
    return $price . '<span class="price-description">' . $textafter . '</span>';
 } 
 else 
 { 
    return $price; 
 } 
}
add_filter( 'woocommerce_get_price_html', 'themeprefix_custom_price_message' );

但是,现在我需要添加另一组产品,并在价格后启用不同的文本,即“Each/Min 8”。我已尝试对上述内容进行各种更改,但每次都会导致网站关闭。如何调整上述内容以在价格后添加另一组(然后可能是另一组)具有不同文本的产品 ID?提前致谢!

最佳答案

此答案适用于此处提出的问题:Add custom text after the price in WooCommerce

但是,它也可以用在上面的问题中。

如果您想在每个产品后添加动态文本,您可以尝试类似的方法。

/* add custom field in single product */

add_action('woocommerce_product_options_general_product_data', function() {
    woocommerce_wp_text_input([
            'id' => '_custom_text_after_price',
            'label' => __('Custom Text after Price', 'themedomain'),
    ]);
});

您可以在您的产品中看到上述更改。

enter image description here

现在添加以下代码以将元数据保存在您的产品中

/* save meta field */
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');
function woocommerce_product_custom_fields_save($post_id)
{
    $woocommerce_custom_product_text_field = $_POST['_custom_text_after_price'];
    if (!empty($woocommerce_custom_product_text_field))
        update_post_meta($post_id, '_custom_text_after_price', esc_attr($woocommerce_custom_product_text_field));
}

现在要在前端显示自定义代码,您需要使用 2 个钩子(Hook)。

/* show custom text on front end */
function cw_change_product_price_display( $price ) {
    global $post, $product;
    if(get_post_meta( $post->ID, '_custom_text_after_price', true )){
        $text = get_post_meta( $post->ID, '_custom_text_after_price', true );
    }
    $price .= ' '.$text;
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );

在前端,它看起来像这样。

enter image description here

关于php - 在每个产品 ID/WP 的 WooCommerce 产品价格后添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60693560/

相关文章:

wordpress - 如何在 laravel 公用文件夹中安装 wordpress

wordpress - 在 Docker 容器之间可以 ping 但不能 wget

mysql - 高级 Wordpress MySQL 查询选择产品和属性

php - 以编程方式更新 Woocommerce 订单的修改日期

php - 自用户上次使用 PHP 和 MySQL 登录以来的时间

php - 如何在 PHP 中加入两个 MySQL 查询

wordpress - NGINX 尾部斜杠但不包括 wp-json 和 wp-admin

php - WooCommerce 检查购物车商品数量是否为 6 的倍数(从 12 开始)

php - 我可以在 PHP 中混合 MySQL API 吗?

php - 如何将当前站点的用户表(mysql+md5 密码)迁移到新的 django postgres 设置?