2016-01-27 4 views
0

я создал два пользовательских полей в вариациях с помощью следующего кода (Спасибо Remi Corso):Показать пользовательских полей в странице продукта вариации WooCommerce

functions.php

Добавить Настройки Вариация

add_action('woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3); 

Сохранить изменения Настройки

add_action('woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2); 

Создайте новые поля для v ariations

function variation_settings_fields($loop, $variation_data, $variation) { 
    woocommerce_wp_text_input( 
     array( 
      'id'   => '_pdf_ficha_tecnica[' . $variation->ID . ']', 
      'label'  => __('PDF FICHA TÉCNICA', 'woocommerce'), 
      'placeholder' => 'http://', 
      'desc_tip' => 'true', 
      'description' => __('aqui', 'woocommerce'), 
      'value'  => get_post_meta($variation->ID, '_pdf_ficha_tecnica', true) 
     ) 
    ); 
    woocommerce_wp_text_input( 
     array( 
      'id'   => '_pdf_ficha_caracteristicas[' . $variation->ID . ']', 
      'label'  => __('PDF FICHA CARACTERÍSTICAS', 'woocommerce'), 
      'placeholder' => 'http://', 
      'desc_tip' => 'true', 
      'description' => __('aqui', 'woocommerce'), 
      'value'  => get_post_meta($variation->ID, '_pdf_ficha_caracteristicas', true) 
     ) 
    ); 
} 

Сохранить новые поля для вариаций

function save_variation_settings_fields($post_id) { 
    $text_field = $_POST['_pdf_ficha_tecnica'][ $post_id ]; 
    if(! empty($text_field)) { 
     update_post_meta($post_id, '_pdf_ficha_tecnica', esc_attr($text_field)); 
    } 
    $text_field = $_POST['_pdf_ficha_caracteristicas'][ $post_id ]; 
    if(! empty($text_field)) { 
     update_post_meta($post_id, '_pdf_ficha_caracteristicas', esc_attr($text_field)); 
    } 
} 

Этих пользовательских полей хранить URL-адрес и будет отображаться в виде ссылок. Я ищу отображение этих полей, но у меня много проблем, чтобы найти правильное решение.

Может ли кто-нибудь вести меня? Должен ли я сосредоточиться на файле «variable.php»? И JS? Или я могу визуализировать поля крючками?

Заранее благодарен!

+0

В комментариях на уроке Реми есть [эта ссылка] (http://blueskysessions.com/2014/03/31/woocommerce-display-dynamic-content-per-the-selected-product-variation /), которые могут помочь. – helgatheviking

+0

где вы планируете отображать эти поля? – Reigel

+0

Спасибо, что ответили на elgatheviking! Я прочитал эту ссылку. Я новичок в настройке WooCommerce и jQuery. Я не нашел пример кода, который выглядит так, как я хочу. Продолжая поиск, спасибо! –

ответ

0

Следующий код, который я создал, отлично работает. Я новичок в JS, и я уверен, что его можно улучшить. Надеюсь, это будет полезно. Для создания пользовательских полей читается сообщение REMI.

Объяснение: С «WC_Product переменной» объект может отображать пользовательские поля вариации продукта,

Для отображения этих полей я использовал JQuery, содержимое пролете «СКУ» будет наша ссылка, как показано на продукте стр. Этот код в файле "changes.php".

<?php 

// With "WC_Product Variable" object I get the Custom Fields variations. 

$product_id = $product->id; 
$variation = new WC_Product_Variable($product_id); 
$arrvariations = $variation->get_children(); 

// With foreach construct the div that will contain the Custom Fields 

foreach ($arrvariations as $varid) { 
    $cfvalone = get_post_meta($varid, '_custom_field_one', true); 
    $cfvaltwo = get_post_meta($varid, '_custom_field_two', true); 

// Check the Custom Fields are not empty 

    if (!empty($cfvalone) or !empty($cfvaltwo)) { 

     $cfonecont = get_post_meta($varid, '_custom_field_one', true); 
     $cftwocont = get_post_meta($varid, '_custom_field_two', true); 
     $varsku = get_post_meta($varid, '_sku', true); 

// Built the DIV and embed SKU of the variation to be processed later by JS. 
?> 
    <div class="varskudiv" data-varskudiv="<? echo $varsku;?>" style="display:none;"> 
     <?php if (!empty($cfonecont)) {?> 
      <a href="<? echo $cfonecont;?>">CUSTOM FIELD ONE</a> 
     <?php } ?> 
     <?php if (!empty($cftwocont)) {?> 
      <a href="<? echo $cftwocont;?>">CUSTOM FIELD TWO</a> 
     <?php } ?> 
    </div> 
    <? }}?> 
    <br/> 
<script> 
jQuery(document).ready(function($) { 
    // As we will take the contents of SPAN "sku" to create the JS 
    //we must consider that this SPAN is complete once the screen is loaded. 

    $(window).bind("load", function() { 
    woosku = $(".sku").text(); 
    // Now we map the DIV we created "varskudiv" and load those values in an ARRAY 
    wooarrsku = $('div.varskudiv').map(function(){ 
     return $(this).data('varskudiv'); 
    }).get(); 
    // Now we make loop, if the values match show the DIV. 
    var indexsku; 
    for (indexsku = 0; indexsku < wooarrsku.length; indexsku++) { 
    if (woosku == wooarrsku[indexsku]) { 
     $('.varskudiv[data-varskudiv="'+ woosku +'"]').css("display", "inline-block"); 
     } 
    } 
    }); 
    // Once loaded the screen, if the SPAN "sku" changes, start the process again and hide the previous DIV displayed. 

    $('.sku').bind("DOMSubtreeModified",function(){ 
     woosku = $(".sku").text(); 
     wooarrsku = $('div.varskudiv').map(function(){ 
      return $(this).data('varskudiv'); 
     }).get(); 
     var indexsku; 
     for (indexsku = 0; indexsku < wooarrsku.length; indexsku++) { 
     if (woosku == wooarrsku[indexsku]) { 
      $('.varskudiv[data-varskudiv="'+ woosku +'"]').css("display", "inline-block"); 
      } 
     else {$('.varskudiv[data-varskudiv="'+ wooarrsku[indexsku] +'"]').css("display", "none"); 
      } 
     } 
    }); 
}); 
</script> 
+0

Remi обновить код: http://www.remicorson.com/woocommerce-custom-fields-for-variations/ –

 Смежные вопросы

  • Нет связанных вопросов^_^