Home » Php » php – Code only runs on Woocommerce shop page but not on other WordPress/Woocomerce pages

php – Code only runs on Woocommerce shop page but not on other WordPress/Woocomerce pages

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have tried to add a quantity input field to all my WordPress pages which display Woocommerce products. My code adds a quantity input file to all products on all pages as intended but it only processes inputs on the Woocomerce shop page. If the product is on any other page including Woocommerce category pages only the input field is shown but id does not affect anything. Anyone got any idea what I am missing? Thank you.

/**
 * Add quantity field on the archive page.
 */
function custom_quantity_field_archive() {

    $product = wc_get_product( get_the_ID() );

    if ( ! $product->is_sold_individually() && 'variable' != $product->product_type && $product->is_purchasable() ) {
        woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) );
    }

}
add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 0, 9 );


/**
 * Add requires JavaScript.
 */
function custom_add_to_cart_quantity_handler() {

    wc_enqueue_js( '
        jQuery( ".post-type-archive-product" ).on( "click", ".quantity input", function() {
            return false;
        });
        jQuery( ".post-type-archive-product" ).on( "change input", ".quantity .qty", function() {
            var add_to_cart_button = jQuery( this ).parents( ".product" ).find( ".add_to_cart_button" );
            // For AJAX add-to-cart actions
            add_to_cart_button.data( "quantity", jQuery( this ).val() );
            // For non-AJAX add-to-cart actions
            add_to_cart_button.attr( "href", "?add-to-cart=" + add_to_cart_button.attr( "data-product_id" ) + "&quantity=" + jQuery( this ).val() );
        });
    ' );

}
add_action( 'init', 'custom_add_to_cart_quantity_handler' );
How to&Answers:

post-type-archive-product needs to be replaced with type-product