php – Woocommerce我如何在每次变化后获得价格

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – Woocommerce我如何在每次变化后获得价格脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用最新的WC,我真的希望价格显示在每个变体旁边,以获得更好的概览.

我无法为我的functions.PHP找到合适的代码,以显示每个变体旁边的价格.我看到几个较旧的帖子,其中没有人真的有用.

我尝试了以下方法

add_filter( 'woocommerce_VARiation_option_name','display_PRice_in_variation_option_name' );

function display_price_in_variation_option_name( $term ) {
    global $wpdb,$product;

    if ( empty( $term ) ) return $term;
    if ( empty( $product->id ) ) return $term;

    $result = $wpdb->get_col( "SELECT slug From {$wpdb->prefix}terms WHERE name = '$term'" );

    $term_slug = ( !empty( $result ) ) ? $result[0] : $term;

    $query = "SELECT postMeta.post_id AS product_id
                From {$wpdb->prefix}postMeta AS postMeta
                    LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postMeta.post_id )
                WHERE postMeta.Meta_key LIKE 'attribute_%'
                    AND postMeta.Meta_value = '$term_slug'
                    AND products.post_parent = $product->id";

    $variation_id = $wpdb->get_col( $query );

    $parent = wp_get_post_parent_id( $variation_id[0] );

    if ( $parent > 0 ) {
         $_product = new WC_Product_Variation( $variation_id[0] );
         return $term . ' (' . wp_kses( woocommerce_price( $_product->get_price() ),array() ) . ')';
    }
    return $term;

}

解决方法

由于没有id参数woocommerce_variation_option_name,我们可以使用脚本执行此操作.

add_action( "wp_head","function_to_woo_script" );

function function_to_woo_script () {
    ?>
    <script>
    $= jquery;
    $(document).ready(function(){
        var json_product    =   jQuery.parseJSON( $(".variations_form").attr("data-product_variations") );
        var currency    =   "$";
        for( i = 0; i < json_product.length; i++ ) {
            var attr_name   =   $(".variations select").attr("data-attribute_name");
            $(".variations select option[value='"+json_product[i].attributes[attr_name]+"']").htML( json_product[i].attributes[attr_name] + " - " + currency + json_product[i].display_regular_price );
        }
    });
    </script>
    <?PHP 
}

结果

脚本宝典总结

以上是脚本宝典为你收集整理的php – Woocommerce我如何在每次变化后获得价格全部内容,希望文章能够帮你解决php – Woocommerce我如何在每次变化后获得价格所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。