我使用此代码在商店存档页面上显示每个产品下方的尺寸属性,但它会在下面抛出错误。如何更改代码以修复此错误?我认为代码已经贬值了。
add_action(\'woocommerce_after_shop_loop_item_title\', \'add_attribute\', 5);
function add_attribute() {
$desired_att = \'Size\';
global $product;
$product_variable = new WC_Product_Variable($product->id);
$product_variations = $product_variable->get_available_variations();
$numItems = count($product_variations);
echo \'<span class="price">\';
if ($numItems == 1) {
foreach ($product_variations as $variation) {
echo $variation[attributes][\'attribute_pa_size\'];
}
} else if ($numItems > 1) {
$i = 0;
foreach ($product_variations as $variation) {
if (++$i === $numItems) {
echo $variation[attributes][\'attribute_pa_size\'];
} else {
echo $variation[attributes][\'attribute_pa_size\'] . ", ";
}
}
}
echo \'</span>\';
}
错误消息
Notice: id was called
incorrectly
. Product properties should not be accessed directly. Backtrace: require(\'wp-blog-header.php\'), require_once(\'wp-includes/template-loader.php\'), include(\'/plugins/genesis-connect-woocommerce/templates/taxonomy.php\'), genesis, do_action(\'genesis_loop\'), WP_Hook->do_action, WP_Hook->apply_filters, genesiswooc_product_taxonomy_loop, genesiswooc_content_product, wc_get_template_part, load_template, require(\'/plugins/woocommerce/templates/content-product.php\'), do_action(\'woocommerce_after_shop_loop_item_title\'), WP_Hook->do_action, WP_Hook->apply_filters, add_attribute, WC_Abstract_Legacy_Product->__get, wc_doing_it_wrong Please see
Debugging in WordPress
for more information. (This message was added in version 3.0.) in
/home/public_html/wp-includes/functions.php
on line
4773
最合适的回答,由SO网友:LoicTheAztec 整理而成
您的代码自WooCommerce 3以来已过时
首先,您只需要针对可变产品类型,以避免其他产品类型上的错误,并且$product
已是产品对象。
此外,您还可以直接使用WC_Product
方法get_attribute()
您的代码将更加简单、紧凑和高效:
add_action( \'woocommerce_after_shop_loop_item_title\', \'display_size_attribute\', 5 );
function display_size_attribute() {
global $product;
if ( $product->is_type(\'variable\') ) {
$taxonomy = \'pa_size\';
echo \'<span class="attribute-size">\' . $product->get_attribute($taxonomy) . \'</span>\';
}
}
代码进入函数。活动子主题(或活动主题)的php文件经过测试并正常工作。