问题描述
我正在尝试创建一个 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 (将#修改为@)