简体   繁体   中英

Javascript executing but not keeping value on Woocommerce checkout page

I'm using this in functions.php to execute on Woocommerce checkout page.

I see display: none is being applied but only for couple of miliseconds.

Any idea how to keep the styling on elements?

// add script to checkout page

add_action( 'wp_footer', 'add_javascript_function', 9999 );

function add_javascript_function() {
global $wp;
if ( is_checkout() && empty( $wp->query_vars['order-pay'] ) && ! isset( $wp->query_vars['order-received'] ) ) {
    echo '<script>
 window.addEventListener("DOMContentLoaded", () => {
let myDivs = document.getElementsByClassName("products");
for(let i = 2; i < myDivs.length; i++) {
myDivs[i].style.display="none"; }
 });
 </script>';
}
}

Also would like to add a button to toggle the items being hidden by this function. But this issue is driving me crazy.

Thanks in advance.

Using JS to set the initial visibility of your HTML elements won't work because after your function has run update_checkout is triggered which refreshes the order review part of the checkout. That is why you see your styles only being applied briefly.

You should use CSS to set the visibility of your products, then use JS to overrule those styles when clicking on a button, toggling between hidden and visible.

The woocommerce_review_order_after_cart_contents hook gives you a nice place to add a button for this. You can also add your CSS and JS there so everything is wrapped up in one neat little function. Like this:

add_action ('woocommerce_review_order_after_cart_contents', function() {
    ?>
    <style>
        .woocommerce-checkout-review-order-table .cart_item:nth-child(n+3) {
            display: none;
        }
    </style>
    <script>
        jQuery( function( $ ) {
            $( '#product-toggle' ).on( 'click', 'span.button', function() {
                if ( $( this ).data( 'show' ) === true ) {
                    $( '.woocommerce-checkout-review-order-table .cart_item').show();
                    $( this ).text( 'Show less products' ).data( 'show', false );
                } else {
                    $( '.woocommerce-checkout-review-order-table .cart_item').slice(2).hide();
                    $( this ).text( 'Show all products' ).data( 'show', true );
                }
            } );
        } );
    </script>
    <?php
    
    echo '<tr id="product-toggle"><td colspan="2"><span class="button" data-show="true">Show all products</span></td></tr>';
}, 10 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM