Добавить настраиваемое поле на вкладку дополнительного изображения (переименовано в спецификацию), без плагина - PullRequest
0 голосов
/ 25 мая 2019

Я пытаюсь добавить настраиваемое поле на вкладку атрибутов продукта.В нашем случае мы переименовали его в спецификацию, но не уверены, что это имеет значение.

Вот код для создания пользовательских полей, и я могу успешно манипулировать ими и размещать их на странице продукта, но не вВкладка product_attributes.

Вкладка product_attributes всегда существует для каждого продукта на нашем сайте с указанием способа его построения.

Код:

// Test in Additional Info
// -----------------------------------------
// 1. Add custom field input @ Product Data > Variations > Single Variation

add_action( 'woocommerce_variation_options_pricing', 'bbloomer_add_test_cf_to_variations', 10, 3 ); 

function bbloomer_add_test_cf_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input( array( 
'id' => 'test_cf[' . $loop . ']', 
'class' => 'short', 
'label' => __( 'Test', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'test_cf', true )
) 
);      
}

// -----------------------------------------
// 2. Save custom field on product variation save

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

function bbloomer_save_test_cf_variations( $variation_id, $i ) {
    $test_cf = $_POST['test_cf'][$i];
    if ( ! empty( $test_cf ) ) {
        update_post_meta( $variation_id, 'test_cf', esc_attr( $test_cf ) );
    } else delete_post_meta( $variation_id, 'test_cf' );
}

// 3. Store custom delivery value into variation data 

add_filter( 'woocommerce_available_variation', 'bbloomer_add_test_cf_variation_data' );

function bbloomer_add_test_cf_variation_data( $variations ) {

    $test = get_post_meta( $variations[ 'variation_id' ], 'test_cf', true );
    if( ! empty( $test ) ) {
    $variations['test_cf'] = '<div>Test: <span>' . get_post_meta( $variations[ 'variation_id' ], 'test_cf', true ) . '</span></div>';
    }
    return $variations;
}

Обычно при добавлении пользовательских полей таким образом, Я бы добавил их в файл переопределения var.php, а затем мог бы манипулировать ими с помощью css.

Я попытался добавить следующее в product-attribute.php:

<script type="text/template" id="tmpl-variation-template">
    <div class="woocommerce-variation-test">{{{ data.variation.test_cf }}}</div>
</script>
<script type="text/template" id="tmpl-unavailable-variation-template">
    <p><?php _e( 'Sorry, this product is unavailable. Please choose a different combination.', 'woocommerce' ); ?></p>
</script>

Но я не могу заставить их отображаться вообще.

1 Ответ

1 голос
/ 25 мая 2019

Я не знаю, что именно должно отображаться там, похоже, вы хотите поделиться информацией о времени доставки?

ШАГ 1

создать функциюв твоих темах functions.php.Я разместил несколько комментариев, чтобы объяснить, что происходит.

 /**
  * Template hook points at product_attributes.php
  *
  * @template product-attributes.php
  */
   add_action('custom_template_hook', 'display_custom_field' , 10 , 1);
    function display_custom_field($product) {
      // Check if product is variable
      if( $product->is_type( 'variable' ) ){
          // If so, get all available variations!
        $variations = $product->get_available_variations();
            // Loop through variations
          foreach ($variations as $variation) {
              // Check if meta field isn't empty, if not display the field!
            if (!empty(get_post_meta( $variation['variation_id'], 'test_cf', true))) {
                 // get product object from variation ID
                 $product_obj = wc_get_product( $variation['variation_id'] );
              ?>
              <tr class="woocommerce-product-attributes-item">
                <th class="woocommerce-product-attributes-item__label"><?php  echo $product_obj->get_name() ?></th>
                <td class="woocommerce-product-attributes-item__value"><?php echo wp_kses_post( get_post_meta( $variation['variation_id'], 'test_cf', true ) ); ?></td>
              </tr>
              <?
            }
          }
        }
      }

ШАГ 2

В атрибутах продукта это не ловушка, которую вы можете использовать, так что выЯ должен добавить строку кода в product-attribute.php. Лично я бы предложил использовать дочернюю тему, иначе вы можете потерять свои изменения в будущих обновлениях.

do_action('custom_template_hook', $product);

Ваш файл product-attribute.php долженвыглядеть так!

<?php
/**
 * Product attributes
 *
 * Used by list_attributes() in the products class.
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/single-product/product-attributes.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce/Templates
 * @version 3.6.0
 */

defined( 'ABSPATH' ) || exit;

if ( ! $product_attributes ) {
    return;
}


?>
<table class="woocommerce-product-attributes shop_attributes">
    <?php foreach ( $product_attributes as $product_attribute_key => $product_attribute ) : ?>
        <tr class="woocommerce-product-attributes-item woocommerce-product-attributes-item--<?php echo esc_attr( $product_attribute_key ); ?>">
            <th class="woocommerce-product-attributes-item__label"><?php echo wp_kses_post( $product_attribute['label'] ); ?></th>
            <td class="woocommerce-product-attributes-item__value"><?php echo wp_kses_post( $product_attribute['value'] ); ?></td>
        </tr>
    <?php endforeach; 
        do_action('custom_template_hook', $product);
    ?>
</table>

Надеюсь, это поможет, если у вас возникнут какие-либо проблемы, дайте мне знать!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...