我在子主题functions.php 文件中有一些代码,向 WooCommerce 管理产品选项添加了几个自定义字段。它已经工作了几年,没有任何问题,但现在我收到如下 PHP 警告:
PHP 警告:/home/xxx/public_html/wp-content/themes/flatsome-cobra/functions.php(65) 中未定义变量 $post :第 4 行的 eval() 代码 PHP 警告:尝试读取 /home/xxx/wp-content/themes/flatsome-cobra/functions.php(65) 中 null 的属性“ID”:第 4 行的 eval() 代码
这是代码:
<?php
// Add custom Theme Functions here
// Display Fields
add_action('woocommerce_product_options_inventory_product_data', 'woocommerce_product_custom_fields');
// Save Fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');
function woocommerce_product_custom_fields()
{
global $woocommerce, $post;
echo '<div class="product_custom_field">';
// Custom Part Number Text Field
woocommerce_wp_text_input(
array(
'id' => '_part_number',
'placeholder' => 'Part Number (Short SKU)',
'label' => __('Part Number', 'woocommerce'),
'desc_tip' => 'true'
)
);
// Custom Part Ref Text Field
woocommerce_wp_text_input(
array(
'id' => '_part_ref',
'placeholder' => 'Part Ref (Schematic Ref)',
'label' => __('Part Ref', 'woocommerce'),
'desc_tip' => 'true'
)
);
echo '</div>';
}
function woocommerce_product_custom_fields_save($post_id)
{
// Custom Part Number Text Field
$woocommerce_part_number = $_POST['_part_number'];
if (!empty($woocommerce_part_number))
update_post_meta($post_id, '_part_number', esc_attr($woocommerce_part_number));
// Custom Part Ref Text Field
$woocommerce_part_ref = $_POST['_part_ref'];
if (!empty($woocommerce_part_ref))
update_post_meta($post_id, '_part_ref', esc_attr($woocommerce_part_ref));
}
请问,有人知道需要进行哪些更改才能消除警告吗?
我已经抑制了网页上的警告,但我想这需要针对未来的 PHP 版本进行纠正,我正在使用 PHP 8.1。
自 WooCommerce 3 以来,您的代码有点过时,请尝试以下操作:
// Display Fields
add_action('woocommerce_product_options_inventory_product_data', 'display_admin_product_custom_input_fields');
function display_admin_product_custom_input_fields() {
echo '<div class="product_custom_field">';
woocommerce_wp_text_input( array(
'id' => '_part_number',
'placeholder' => __('Part Number (Short SKU)', 'woocommerce'),
'label' => __('Part Number', 'woocommerce'),
'desc_tip' => 'true'
) );
woocommerce_wp_text_input( array(
'id' => '_part_ref',
'placeholder' => __('Part Ref (Schematic Ref)', 'woocommerce'),
'label' => __('Part Ref', 'woocommerce'),
'desc_tip' => 'true'
) );
echo '</div>';
}
// Save Field values
add_action('woocommerce_admin_process_product_object', 'save_admin_product_custom_field_values', 10, 1);
function save_admin_product_custom_field_values($product) {
if ( isset($_POST['_part_number'])){
$product->update_meta_data('_part_number', sanitize_text_field($_POST['_part_number']));
}
if ( isset($_POST['_part_ref'])){
$product->update_meta_data('_part_ref', sanitize_text_field($_POST['_part_ref']));
}
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。
它应该可以解决 PHP 警告。