Woocommerce Проблема с крючками для одного продукта: заменить кнопку «Добавить в корзину»

Я создал новую ФУНКЦИЮ для страницы своего продукта.

Там написано, КОГДА _shipping_costs пусто (без цифр), затем измените кнопку на «цена по запросу».

Страница архива

На странице архива вы можете ясно видеть, что все работает отлично.

Но я пытаюсь изменить кнопку на одной странице продукта.

Отдельная страница продукта

Это строится следующим образом.

Новая функция кнопки:

function custom_add_price_on_request_button() {
    global $product;
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
    if ($shipping_cost === '') {
        echo '<a class = "button price-on-request-button" href = "mailto:[email protected]"><span>Prijs op</span><span>aanvraag</span></a>';
    }
}
add_action('woocommerce_after_shop_loop_item', 'custom_add_price_on_request_button', 11);

Удалить кнопку + добавить новую функцию кнопки:

function custom_remove_and_add_cart_button_single() {
    global $product;
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);

    if ($shipping_cost === '') {
        // Remove the default add to cart button
        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
        remove_action('woocommerce_single_product_summary', 'woocommerce_single_variation_add_to_cart_button', 30);
        
        // Add a custom 'Prijs op aanvraag' button
        add_action('woocommerce_single_product_summary', 'custom_add_price_on_request_button', 35);
    }
}
add_action('woocommerce_before_single_product_summary', 'custom_remove_and_add_cart_button_single', 1);

Как вы можете видеть, там написано ЕСЛИ стоимость доставки === '' (пусто), затем удалите кнопку «Добавить в корзину» и замените ее на «кнопку новой функции».

Как вы также можете видеть на странице архива, все работает нормально, но не на странице одного продукта. Кто-нибудь видит, что не так с крючком Woocommerce, который я использую?

Я нашел несколько веб-сайтов с информацией Wooks, но не вижу возможности это исправить: https://wcsuccessacademy.com/woocommerce-visual-hook-guide-single-product-page/

Полный код работает для страницы архива, но не для отдельной страницы продукта.

 // Update the price display for products with no shipping cost
function custom_price_on_request($price, $product) {
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
    if ($shipping_cost === '') {
        return '<span class = "price-on-request">Prijs op aanvraag</span>';
    }
    return $price;
}
add_filter('woocommerce_get_price_html', 'custom_price_on_request', 10, 2);




// Remove the 'Add to Cart' button if there are no shipping costs on archive pages
function custom_remove_add_to_cart_button_loop() {
    global $product;
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
    if ($shipping_cost === '') {
        remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10);
    }
}
add_action('woocommerce_before_shop_loop_item', 'custom_remove_add_to_cart_button_loop', 1);




// Verwijder de 'Toevoegen aan winkelwagen' knop op enkele productpagina's en voeg 'Prijs op aanvraag' knop toe
function custom_remove_and_add_cart_button_single_product() {
    global $product;
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);

    if ($shipping_cost === '') {
        // Verwijder de standaard 'add to cart' knop
        remove_action('woocommerce_simple_add_to_cart', 'woocommerce_simple_add_to_cart', 30);
        remove_action('woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20);
        
        // Voeg een aangepaste 'Prijs op aanvraag' knop toe
        add_action('woocommerce_simple_add_to_cart', 'custom_add_price_on_request_button', 30);
        add_action('woocommerce_single_variation', 'custom_add_price_on_request_button', 20);
    }
}




// Filter the add to cart button link verwijderd "toevoegen aan winkelwagen" en behoudt "prijs op aanvraag"
function custom_add_to_cart_button($link, $product) {
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
    if ($shipping_cost === '') {
        return ''; // Return an empty string to remove the button
    }
    return $link;
}
add_filter('woocommerce_loop_add_to_cart_link', 'custom_add_to_cart_button', 10, 2);

// Add a custom button with 'Prijs op aanvraag'
function custom_add_price_on_request_button() {
    global $product;
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
    if ($shipping_cost === '') {
        echo '<a class = "button price-on-request-button" href = "mailto:[email protected]"><span>Prijs op</span><span>aanvraag</span></a>';
    }
}
add_action('woocommerce_after_shop_loop_item', 'custom_add_price_on_request_button', 11); // for loop pages

// Add custom CSS to make the button style the same
function custom_price_on_request_styles() {
    echo '<style>
        .price-on-request-button {
            background-color: #4caf50; /* Same background color */
            color: #ffffff; /* Same text color */
            border: 1px solid #4caf50; /* Same border */
            padding: 10px 30px; /* Same padding */
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
            box-shadow: 0 4px #999; /* Added shadow */
        }
        .price-on-request-button span {
            display: block;
        }
    </style>';
}
add_action('wp_head', 'custom_price_on_request_styles');

🤔 А знаете ли вы, что...
В PHP есть много встроенных функций для работы с строками, массивами и файлами.


59
1

Ответ:

Решено

Решение найдено!

// Update the price display for products with no shipping cost
function custom_price_on_request($price, $product) {
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
    if ($shipping_cost === '') {
       return '<span class = "price-on-request">Prijs op aanvraag</span>';
    }
    return $price;
}
add_filter('woocommerce_get_price_html', 'custom_price_on_request', 10, 2);

// Remove the 'Add to Cart' button if there are no shipping costs on archive pages
function custom_remove_add_to_cart_button_loop() {
    global $product;
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
    if ($shipping_cost === '') {
        remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10);
    }
}
add_action('woocommerce_before_shop_loop_item', 'custom_remove_add_to_cart_button_loop', 1);

// Verwijder de 'Toevoegen aan winkelwagen' knop op enkele productpagina's en voeg 'Prijs op aanvraag' knop toe
function custom_remove_and_add_cart_button_single() {
    global $product;
    if (is_string($product)) {
        $product = wc_get_product();
    }
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);

    if ($shipping_cost === '') {
        // Verwijder de standaard 'add to cart' knop
        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
        
        // Voeg een aangepaste 'Prijs op aanvraag' knop toe
        add_action('woocommerce_single_product_summary', 'custom_add_price_on_request_button_single', 30);
    }
}
add_action('woocommerce_before_single_product_summary', 'custom_remove_and_add_cart_button_single', 1);

// Filter the add to cart button link verwijderd "toevoegen aan winkelwagen" en behoudt "prijs op aanvraag"
function custom_add_to_cart_button($link, $product) {
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
    if ($shipping_cost === '') {
        return ''; // Return an empty string to remove the button
    }
    return $link;
}
add_filter('woocommerce_loop_add_to_cart_link', 'custom_add_to_cart_button', 10, 2);

// Add a custom button with 'Prijs op aanvraag'
function custom_add_price_on_request_button() {
    global $product;
    if (!is_a($product, 'WC_Product')) {
        return; // Exit if $product is not a valid WC_Product object
    }
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
    if ($shipping_cost === '') {
        echo '<a class = "button price-on-request-button" href = "mailto:[email protected]"><span>Prijs op</span><span>aanvraag</span></a>';
    }
}
add_action('woocommerce_after_shop_loop_item', 'custom_add_price_on_request_button', 11); // for loop pages

function custom_add_price_on_request_button_single() {
    global $product;
    if (is_string($product)) {
        $product = wc_get_product();
    }
    if (!is_a($product, 'WC_Product')) {
        return; // Exit if $product is not a valid WC_Product object
    }
    $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
    if ($shipping_cost === '') {
        echo '<a class = "button price-on-request-button" href = "mailto:[email protected]"><span>Prijs op aanvraag</span></a>';
    }
}

// Elementor specific hook to remove the default add to cart button and add the custom button
add_action('elementor/frontend/after_render', function() {
    if (is_product()) {
        global $product;
        if (is_string($product)) {
            $product = wc_get_product();
        }
        $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
        if ($shipping_cost === '') {
            // Verwijder de standaard 'add to cart' knop
            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
            
            // Voeg een aangepaste 'Prijs op aanvraag' knop toe
            if (!did_action('custom_price_on_request_button_added')) {
                custom_add_price_on_request_button_single();
                do_action('custom_price_on_request_button_added');
            }
        }
    }
});

add_filter('body_class', function($classes) {
    if (is_product()) {
        global $product;
        if (is_string($product)) {
            $product = wc_get_product();
        }
        $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
        $shipping_cost_class = empty($shipping_cost) ? 'no-shipping-cost' : 'has-shipping-cost';
        $classes[] = $shipping_cost_class;
    }
    return $classes;
});

// JavaScript toevoegen om de knop "Toevoegen aan winkelwagen" dynamisch te verwijderen
function custom_add_to_cart_button_js() {
    ?>
    <script type = "text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            if (document.body.classList.contains('no-shipping-cost')) {
                var addToCartButton = document.querySelector('.single_add_to_cart_button');
                if (addToCartButton) {
                    addToCartButton.remove();
                }

                var priceOnRequestButton = document.querySelector('.price-on-request-button');
                if (priceOnRequestButton) {
                    var cartForm = document.querySelector('form.cart');
                    if (cartForm) {
                        cartForm.appendChild(priceOnRequestButton);
                    }
                }
            }
        });
    </script>
    <?php
}
add_action('wp_footer', 'custom_add_to_cart_button_js');


// Add custom CSS to make the button style the same
function custom_price_on_request_styles() {
    echo '<style>
        .price-on-request-button {
            background-color: #4caf50; /* Same background color */
            color: #ffffff; /* Same text color */
            border: 1px solid #4caf50; /* Same border */
            padding: 10px 30px; /* Same padding */
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 4px;
            box-shadow: 0 4px #999; /* Added shadow */
        }
        .price-on-request-button span {
            display: block;
        }
        body.no-shipping-cost .elementor-widget-container .quantity {
            display: none;
        }
    </style>';
}
add_action('wp_head', 'custom_price_on_request_styles');

Важная часть кнопки Elementor «ДОБАВИТЬ В КОРЗИНУ»

// Elementor specific hook to remove the default add to cart button and add the custom button
add_action('elementor/frontend/after_render', function() {
    if (is_product()) {
        global $product;
        if (is_string($product)) {
            $product = wc_get_product();
        }
        $shipping_cost = get_post_meta($product->get_id(), '_shipping_cost', true);
        if ($shipping_cost === '') {
            // Verwijder de standaard 'add to cart' knop
            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
            
            // Voeg een aangepaste 'Prijs op aanvraag' knop toe
            if (!did_action('custom_price_on_request_button_added')) {
                custom_add_price_on_request_button_single();
                do_action('custom_price_on_request_button_added');
            }
        }
    }
});

// JavaScript toevoegen om de knop "Toevoegen aan winkelwagen" dynamisch te verwijderen
function custom_add_to_cart_button_js() {
    ?>
    <script type = "text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            var addToCartButton = document.querySelector('.single_add_to_cart_button');
            if (addToCartButton) {
                addToCartButton.remove();
            }

            var priceOnRequestButton = document.querySelector('.price-on-request-button');
            if (priceOnRequestButton) {
                var cartForm = document.querySelector('form.cart');
                if (cartForm) {
                    cartForm.appendChild(priceOnRequestButton);
                }
            }
        });
    </script>
    <?php
}
add_action('wp_footer', 'custom_add_to_cart_button_js');