AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79560069
Accepted
OverdueOrange
OverdueOrange
Asked: 2025-04-07 21:55:56 +0800 CST2025-04-07 21:55:56 +0800 CST 2025-04-07 21:55:56 +0800 CST

Como alterar / para o texto de x meses em um produto de assinatura variável WooCommerce

  • 772

Semelhante a este , mas não totalmente.

Tenho um produto de assinatura variável que pode ser pago em 12 parcelas mensais.

se "Número de parcelas" for "Pagar integralmente", gostaria de poder alterar o texto £xxx para 1 mês:Pagar integralmente

E então mantenha as próximas 11 parcelas como para 2 meses / 3 meses, etc.

Sei que esse código só mostrará os preços, mas não consigo modificá-lo para alterar apenas 1 mês (opção de pagamento integral):

add_filter('woocommerce_subscriptions_product_price_string_inclusions', 'remove_subscription_inclusions', 10, 2);

function remove_subscription_inclusions( $include, $product ) {
    $include['subscription_length'] = '';
    $include['subscription_period'] = '';
    return $include;
}

Eu tentei isso, mas não teve efeito algum:

add_filter('woocommerce_subscriptions_product_price_string_inclusions', 'custom_subscription_price_string_inclusions', 10, 2);

function custom_subscription_price_string_inclusions( $include, $product ) {
    // Check if the product is a subscription product
    if ($product->is_type('subscription')) {
        // Get the variations of the subscription product
        $variations = $product->get_available_variations();

        // Loop through each variation to check for the 1-month payment option
        foreach ($variations as $variation) {
            // Get the variation's price and subscription length/period
            $regular_price = $variation['display_price'];
            $subscription_length = isset($variation['attributes']['pa_subscription_length']) ? $variation['attributes']['pa_subscription_length'] : '';
            $subscription_period = isset($variation['attributes']['pa_subscription_period']) ? $variation['attributes']['pa_subscription_period'] : '';

            // Check if this variation is the 1 month (single payment) option
            if ('1' === $subscription_length && 'month' === $subscription_period) {
                // Modify the price string for the 1 month single payment option
                $include['price_string'] = '£' . $regular_price . ' (Full payment for 1 month)';
                // Remove subscription length and period to avoid duplication
                $include['subscription_length'] = '';
                $include['subscription_period'] = '';
            }
        }
    }

    return $include;
}

wordpress
  • 2 2 respostas
  • 69 Views

2 respostas

  • Voted
  1. Kisded Szabi - CodeRevolution
    2025-04-08T19:05:45+08:002025-04-08T19:05:45+08:00

    O woocommerce_subscriptions_product_price_string_inclusionsfiltro só lhe dá controle sobre quais peças são incluídas na sequência de preço final, mas não permite que você altere a sequência inteira ou a personalize por variação facilmente.

    Se você quiser realmente alterar a string de preço , use o código abaixo.

    Este filtro permite que você substitua o resultado final. Esta é uma versão que faz o que você procura: exibe "Pagar à Vista" quando se trata da opção de 1 mês (pagamento único) e mantém o valor usual de "£xx / mês" para as demais.

    
    add_filter( 'woocommerce_subscriptions_product_price_string', 'custom_variable_subscription_price_string', 10, 2 );
    function custom_variable_subscription_price_string( $price_string, $product ) {
        if ( ! is_a( $product, 'WC_Product' ) ) {
            return $price_string;
        }
    
        if ( $product->is_type( 'variation' ) || $product->is_type( 'subscription_variation' ) ) {
            $subscription_length = method_exists( $product, 'get_subscription_length' ) ? $product->get_subscription_length() : 0;
            $subscription_period = method_exists( $product, 'get_subscription_period' ) ? $product->get_subscription_period() : '';
    
            if ( $subscription_length && $subscription_period ) {
                if ( intval( $subscription_length ) === 1 && strtolower( $subscription_period ) === 'month' ) {
                    $price_string = 'Pay in Full';
                }
            }
        }
    
        return $price_string;
    }
    
    • 0
  2. Best Answer
    OverdueOrange
    2025-04-08T21:06:27+08:002025-04-08T21:06:27+08:00

    Foi assim que fiz funcionar: usei javascript/jQuery, pois eles funcionam independentemente das diferenças de classe interna do WooCommerce.

    add_action('wp_footer', 'custom_replace_subscription_price_label');
    
    function custom_replace_subscription_price_label() {
        // Only run this script on single product pages
        if (!is_product()) return;
    
        // Output JavaScript to modify price display dynamically
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                // Hook into variation change event on product page
                $('form.variations_form').on('show_variation', function(event, variation) {
                    
                    // Find the price container
                    var $priceEl = $('.woocommerce-variation-price .price');
    
                    // If variation or price data is missing, stop here
                    if (!variation || !variation.price_html) return;
    
                    // Grab the HTML of the price string
                    const rawHTML = variation.price_html;
    
                    // If the price string contains "for 1 month", replace it
                    if (rawHTML.includes('for 1 month')) {
                        const updatedHTML = rawHTML.replace(/for 1 month/, 'Pay in Full');
                        
                        // Update the HTML in the DOM with the new version
                        $priceEl.html(updatedHTML);
                    }
                });
            });
        </script>
        <?php
    }
    
    //FOR CART & CHECKOUT
    
    // Modify the price column in the cart
    add_filter('woocommerce_cart_item_price', 'custom_replace_subscription_price_cart', 10, 3);
    
    // Modify the subtotal column in the cart
    add_filter('woocommerce_cart_item_subtotal', 'custom_replace_subscription_price_cart', 10, 3);
    
    function custom_replace_subscription_price_cart($price_html, $cart_item, $cart_item_key) {
        // Check if the price string contains "for 1 month"
        if (strpos($price_html, 'for 1 month') !== false) {
            // Replace it with "Pay in Full"
            $price_html = str_replace('for 1 month', 'Pay in Full', $price_html);
        }
    
        // Return the modified (or unmodified) price string
        return $price_html;
    }
    
    • 0

relate perguntas

  • Ocultar preços de produtos para usuários em categorias ou categorias específicas no WooCommerce

  • Definir padrão "Gerenciar estoque?" para "sim" quando uma nova variação é criada (Woocommerce)

  • Faça o título da postagem no wordpress contendo o ID para uma nova postagem criada com wp_insert_post()

  • Famoso processo de instalação do WordPress de cinco minutos após a migração do site

  • O limite de uso de entrada/saída no meu site wordpress atingiu o máximo

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve