WordPress 商城开发 WooCommerce 插件创建自定义产品类型Product_type 并在前端页面循环中隐藏

来源: 老季博客
日期: 2022-5-13
作者: 腾讯云/服务器VPS推荐评测/Vultr
阅读数: 55

近日老季在Wordpress的商城插件Woocommerce开发中,创建自定义的产品product_type类型,下面给出代码段实例:


add_filter( 'product_type_selector', 'pd_add_jappt_product_type' );
 
function pd_add_jappt_product_type( $types ){
    $types[ 'jappt_service' ] = 'Jappt Service';
    return $types;
}
 
/* 
 * Add New Product Type Class
 */

add_action( 'init', 'pd_create_jappt_product_type' );
 
function pd_create_jappt_product_type(){
    class WC_Product_Jappt_Service extends WC_Product {
        public function get_type() {
            return 'jappt_service';
        }
    }
}
 
/* 
 * Load New Product Type Class
 */

add_filter( 'woocommerce_product_class', 'pd_woocommerce_product_class', 10, 2 );
 
function pd_woocommerce_product_class( $classname, $product_type ) {
    if ( $product_type == 'jappt_service' ) { 
        $classname = 'WC_Product_Jappt_Service';
    }
    return $classname;
}


// Adding Price fields & inventory to jappt product type
add_action('admin_footer', 'pd_jappt_product_admin_jappt_js');
function pd_jappt_product_admin_jappt_js() {

    if ('product' != get_post_type()) :
        return;
    endif;
    ?>
    <script type='text/javascript'>
        jQuery(document).ready(function () {
            //for Price tab
            jQuery('.options_group.pricing').addClass('show_if_jappt_service').show();
            // //for Inventory tab
            // jQuery('.inventory_options').addClass('show_if_jappt').show();
            // jQuery('#inventory_product_data ._manage_stock_field').addClass('show_if_jappt').show();
            // jQuery('#inventory_product_data ._sold_individually_field').parent().addClass('show_if_jappt').show();
            // jQuery('#inventory_product_data ._sold_individually_field').addClass('show_if_jappt').show();
        });
    </script>
    <?php
}


// add the settings under ‘General’ sub-menu
add_action( 'woocommerce_product_options_general_product_data', 'pd_add_jappt_settings' );
function pd_add_jappt_settings() {
    // global $woocommerce, $post;
    echo '<div class="options_group">';

    echo '</div>';
}

jappt_service 这个类型的产品类型,不允许在正常的产品页面loop中展示,下面我们给出代码段实例

add_action( 'woocommerce_product_query', 'hide_jappt_products_type' );
   
function hide_jappt_products_type( $q ) {
    
    if( is_admin() )    
        return;
    $tax_query = (array) $q->get( 'tax_query' );
  
    $tax_query[] = array(
           'taxonomy' => 'product_type',
           'field' => 'slug',
           'terms' => array( 'jappt_service' ), // Category slug here
           'operator' => 'NOT IN'
    );
  
  
    $q->set( 'tax_query', $tax_query );
  
}

以上代码需要放入对应主题的 functions.php 中才能生效。

链接到文章: https://jiloc.com/47771.html

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注