微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用会员计划变体的自定义 WooCommerce 定价页面

如何解决使用会员计划变体的自定义 WooCommerce 定价页面

我正在尝试创建一个 WooCommerce 定价页面,我正在使用基于 How to use variation and add-to-cart button outside woocommerce loop 答案代码的以下代码,以显示此定价页面上的变化。

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,'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' );

示例用法 [add_to_cart_form id=147]

它适用于一个产品 ID,当我将短代码用于更多产品时,选择的变体不起作用(Chrome 控制台上没有错误)。

如何使其对多个产品 ID 多次工作?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。