如何在woocommerce循环之外使用变化和添加到购物车按钮

bru*_*496 3 php wordpress woocommerce

我在我的网站上使用 woocommerce,但由于我只有一个主要产品和两个配件(相关产品),我不需要经典的商店页面,也不需要每个产品的单一产品页面。我的主要产品有颜色变化。

我想要一个添加到购物车的按钮,在我的常规帖子页面之一中带有颜色变化下拉列表和数量字段。就像在单个产品页面上一样,但嵌入在我自己的页面中,并且没有我不需要的单个产品页面的部分(描述,...)。

我最终决定使用我创建的两个自定义短代码来实现这一点:[my_vc_product_price id="xxx"][my_vc_add2cart_variable_product id="xxx"]. 所以我可以把它们放在我想要的地方。

但我的问题是下拉菜单+变体可用性+添加到购物车按钮的行为与单个产品页面中该元素的行为不同:-当我选择时,变体的可用性不显示下拉菜单中的颜色;- 当下拉菜单中没有选择颜色时,添加到购物车按钮不会被禁用(它应该被禁用并只有在选择了一种颜色时才处于活动状态)。

显示价格很容易,使用一些在互联网上找到的代码:

/**
 * Add shortcode to allow to display product price in a page
 */ 
function my_vc_display_product_price( $args ) {
    $product_id = $args['id'];
    $product = wc_get_product( $product_id );
    echo '<p class="price">' . $product->get_price_html() . '</p>';

}
add_shortcode( 'my_vc_product_price', 'my_vc_display_product_price');
Run Code Online (Sandbox Code Playgroud)

为了获得相同的图形结果,我只需要在行中添加一些 CSS 类:“woocommerce”和“product”。

显示下拉菜单 + 数量和添加到购物车按钮的代码与 plugins/woocommerce/templates/single-product/add-to-cart/ 中的 variable.php 文件几乎相同。唯一真正改变的是您需要获取产品的“变体属性”,而不是属性。

$attributes = $product->get_variation_attributes();
$attribute_keys = array_keys( $attributes );
Run Code Online (Sandbox Code Playgroud)

所以完整的函数代码是:

/**
 * Add shortcode to allow to display an add to cart button with dropdown menu for variation attributes
 */ 
function my_vc_add_to_cart_button_variable_product( $args ) {
    global $product;
    $product_id = $args['id'];
    $product = wc_get_product( $product_id );
    if( $product->is_type( 'variable' )) {
        $attributes = $product->get_variation_attributes();
        $attribute_keys = array_keys( $attributes );
        $available_variations = array( $product->get_available_variations() );

        do_action( 'woocommerce_before_add_to_cart_form' ); ?>

        <form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->get_id() ); ?>" data-product_variations="<?php echo htmlspecialchars( wp_json_encode( $available_variations ) ) ?>">
            <?php do_action( 'woocommerce_before_variations_form' ); ?>

            <?php if ( empty( $available_variations ) && false !== $available_variations ) : ?>
                <p class="stock out-of-stock"><?php _e( 'This product is currently out of stock and unavailable.', 'woocommerce' ); ?></p>
            <?php else : ?>
                <table class="variations" cellspacing="0">
                    <tbody>
                        <?php foreach ( $attributes as $attribute_name => $options ) : ?>
                            <tr>
                                <td class="value">
                                    <?php
                                        $selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( stripslashes( urldecode( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ) ) : $product->get_variation_default_attribute( $attribute_name );
                                        wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach;?>
                    </tbody>
                </table>

                <?php do_action( 'woocommerce_before_add_to_cart_button' ); ?>

                <div class="single_variation_wrap">
                    <?php
                        /**
                         * woocommerce_before_single_variation Hook.
                         */
                        do_action( 'woocommerce_before_single_variation' );

                        /**
                         * woocommerce_single_variation hook. Used to output the cart button and placeholder for variation data.
                         * @since 2.4.0
                         * @hooked woocommerce_single_variation - 10 Empty div for variation data.
                         * @hooked woocommerce_single_variation_add_to_cart_button - 20 Qty and cart button.
                         */
                        do_action( 'woocommerce_single_variation' );
                        ?>
                        <script type="text/template" id="tmpl-variation-template">
                            <div class="woocommerce-variation-description">{{{ data.variation.variation_description }}}</div>
                            <div class="woocommerce-variation-price">{{{ data.variation.price_html }}}</div>
                            <div class="woocommerce-variation-availability">{{{ data.variation.availability_html }}}</div>
                        </script>
                        <script type="text/template" id="tmpl-unavailable-variation-template">
                            <p><?php _e( 'Sorry, this product is unavailable. Please choose a different combination.', 'woocommerce' ); ?></p>
                        </script>
                        <?php

                        /**
                         * woocommerce_after_single_variation Hook.
                         */
                        do_action( 'woocommerce_after_single_variation' );
                    ?>
                </div>

                <?php do_action( 'woocommerce_after_add_to_cart_button' ); ?>
            <?php endif; ?>

            <?php do_action( 'woocommerce_after_variations_form' ); ?>
        </form>

        <?php
        do_action( 'woocommerce_after_add_to_cart_form' );
    }
}
add_shortcode( 'my_vc_add2cart_variable_product', 'my_vc_add_to_cart_button_variable_product');
Run Code Online (Sandbox Code Playgroud)

知道出了什么问题吗?我不明白,如果代码相同,为什么不执行相同的代码。由于此代码在 woocommerce 页面之外,是否缺少某些内容?

Raj*_*yde 5

尝试使用以下代码

function add_to_cart_form_shortcode( $atts ) {
        if ( empty( $atts ) ) {
            return '';
        }

        if ( ! isset( $atts['id'] ) && ! isset( $atts['sku'] ) ) {
            return '';
        }

        $args = array(
            'posts_per_page'      => 1,
            'post_type'           => 'product',
            'post_status'         => 'publish',
            'ignore_sticky_posts' => 1,
            'no_found_rows'       => 1,
        );

        if ( isset( $atts['sku'] ) ) {
            $args['meta_query'][] = array(
                'key'     => '_sku',
                'value'   => sanitize_text_field( $atts['sku'] ),
                'compare' => '=',
            );

            $args['post_type'] = array( 'product', 'product_variation' );
        }

        if ( isset( $atts['id'] ) ) {
            $args['p'] = absint( $atts['id'] );
        }

        $single_product = new WP_Query( $args );

        $preselected_id = '0';


        if ( isset( $atts['sku'] ) && $single_product->have_posts() && 'product_variation' === $single_product->post->post_type ) {

            $variation = new WC_Product_Variation( $single_product->post->ID );
            $attributes = $variation->get_attributes();


            $preselected_id = $single_product->post->ID;


            $args = array(
                'posts_per_page'      => 1,
                'post_type'           => 'product',
                'post_status'         => 'publish',
                'ignore_sticky_posts' => 1,
                'no_found_rows'       => 1,
                'p'                   => $single_product->post->post_parent,
            );

            $single_product = new WP_Query( $args );
        ?>
            <script type="text/javascript">
                jQuery( document ).ready( function( $ ) {
                    var $variations_form = $( '[data-product-page-preselected-id="<?php echo esc_attr( $preselected_id ); ?>"]' ).find( 'form.variations_form' );
                    <?php foreach ( $attributes as $attr => $value ) { ?>
                        $variations_form.find( 'select[name="<?php echo esc_attr( $attr ); ?>"]' ).val( '<?php echo esc_js( $value ); ?>' );
                    <?php } ?>
                });
            </script>
        <?php
        }

        $single_product->is_single = true;
        ob_start();
        global $wp_query;

        $previous_wp_query = $wp_query;

        $wp_query          = $single_product;

        wp_enqueue_script( 'wc-single-product' );
        while ( $single_product->have_posts() ) {
            $single_product->the_post()
            ?>
            <div class="single-product" data-product-page-preselected-id="<?php echo esc_attr( $preselected_id ); ?>">
                <?php woocommerce_template_single_add_to_cart(); ?>
            </div>
            <?php
        }

        $wp_query = $previous_wp_query;

        wp_reset_postdata();
        return '<div class="woocommerce">' . ob_get_clean() . '</div>';
}
add_shortcode( 'add_to_cart_form', 'add_to_cart_form_shortcode' );

/*Example Usage [add_to_cart_form id=147]*/
Run Code Online (Sandbox Code Playgroud)