php - 根据 WooCommerce 产品类型显示或隐藏管理自定义设置字段

标签 php jquery wordpress woocommerce product

我制作了自定义字段后端,我希望在简单的产品类型中显示它,并在其他类型中隐藏它。我认为很少有不足以让我实现这一目标。我将不胜感激任何帮助。谢谢! 我添加的代码是:

add_action('admin_head', 'show_this_for_simple_products_and_hide_for_others');
function show_this_for_simple_products_and_hide_for_others() {  
?> 
<script>
    jQuery( function($){

    $( 'body' ).on( 'woocommerce-product-type-change', function( event, select_val, select ) {

        if ( select_val === 'simple' ) {
             // modify to an actual CSS class selector
            $( '.p.form-field.final_product_sku_field' ).show();
        }

    } );

    $( 'select#product-type' ).change();

} );
</script>
<?php
}

最佳答案

已更新

您不需要它,因为已经有一些 CSS 类选择器允许这样做。

要显示“简单”产品类型的字段,您需要在自定义设置字段之间添加(在您的函数内):

echo '<div class="show_if_simple hidden">';

// Your fields here (for "simple" products type only)

echo '</div >';

You can use the show_if_{$product_type} or hide_if_{$product_type} composite class selectors, to show or hide custom settings product fields based on the product type (where {$product_type} need to be replaced by the targeted product type).

It works for all custom product types.

The class selector hidden specify that the content is hidden for non specified product types to be shown.

You can also use those other class selectors like show_if_virtual, hide_if_virtual, show_if_downloadable and hide_if_downloadable.

The class selector options_group adds a separator horizontal line.

这是一个示例(仅针对简单产品显示字段):

add_action( 'woocommerce_product_options_sku', 'add_product_final_sku_custom_field' );
function add_product_final_sku_custom_field(){
    global $post, $product_object;

    echo '<div class="show_if_simple hidden">';

    woocommerce_wp_text_input( array(
        'label' => __( 'Final SKU', 'woocommerce' ),
        'placeholder' => __( 'Enter final SKU here', 'woocommerce' ),
        'id' => 'final_sku',
        'desc_tip' => true,
        'description' => __( 'This SKU is for final use only.', 'woocommerce' ),
    ) );

    echo '</div>';
}

代码位于事件子主题(或事件主题)的functions.php 文件中。经过测试并有效。

您可以看到on the related core html files code source在管理单一产品页面上显示 WooCommerce 产品设置字段。

关于php - 根据 WooCommerce 产品类型显示或隐藏管理自定义设置字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66617046/

相关文章:

javascript - 如何将 PHP 变量从 Blade 格式的 HTML 传递给 JavaScript 函数

javascript - 如何在javascript中检查图像的高度和宽度

javascript - 动态更改背景 url/图像 src 时出错

javascript - 当选择其他选择选项时,用变量值更新选择列表?

php - 将数据插入 WordPress 插件中的新表

php - 如何将 JavaScript 变量传递给 PHP?

php - disk_free_space 和 df,输出差异巨大

php - 编写我的 linux 守护进程的首选方法是什么?

wordpress - SEO 单页 wordpress

wordpress - IE7/8 中的边距和填充问题