KAZ*_*ABE 3 php wordpress attributes product woocommerce
我在 woocommerce 网站(房地产)工作,我无法在我的前台页面上显示产品自定义属性(例如平方米、房间、厕所等)。我正在尝试使用下面的代码,但我可以使其工作。使用我拥有的代码,我只能显示产品 ID,但是当涉及到属性时,当我将属性 ID 放入代码中时,它仅显示单词“Array”或仅显示“Nothing”。
这是我的代码:
add_action('woocommerce_after_shop_loop_item_title', 'cstm_display_product_category', 5);
function cstm_display_product_category()
{
global $product;
$productAttribute = $product->get_id();
//if(isset($productAttribute)){
echo '<div class="items" style="color: #fff;"><p>Output: ' . $productAttribute . '</p></div>';
//}
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处实时查看输出
无论您能给我实现这一目标的任何帮助或指导,我都将非常感激。我在这件事上是个菜鸟。
PD 我将此代码插入到我的functions.php 文件中。
WordPress 是最新的。Woocommerce 是最新的。
更新3
对于产品属性(自定义或非自定义),您可以使用可以输入属性名称、slug 或分类法的WC_Product方法。get_attribute()所以在你的代码中:
add_action('woocommerce_after_shop_loop_item_title', 'display_custom_product_attributes_on_loop', 5 );
function display_custom_product_attributes_on_loop() {
global $product;
$value1 = $product->get_attribute('Square meters');
$value2 = $product->get_attribute('Rooms');
$value3 = $product->get_attribute('Toilets');
if ( ! empty($value1) || ! empty($value2) || ! empty($value3) ) {
echo '<div class="items" style="color: red;"><p>';
$attributes = array(); // Initializing
if ( ! empty($value1) ) {
$attributes[] = __("Square meters:") . ' ' . $value1;
}
if ( ! empty($value2) ) {
$attributes[] = __("Rooms:") . ' ' . $value2;
}
if ( ! empty($value3) ) {
$attributes[] = __("Toilets:") . ' ' . $value3;
}
echo implode( '<br>', $attributes ) . '</p></div>';
}
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。
下面的代码将提供相同的输出,但它经过压缩、优化,并且只需要一组您所需的产品属性:
add_action('woocommerce_after_shop_loop_item_title', 'display_custom_product_attributes_on_loop', 5 );
function display_custom_product_attributes_on_loop() {
global $product;
// Settings: Here below set your product attribute label names
$attributes_names = array('Square meters', 'Rooms', 'Toilets');
$attributes_data = array(); // Initializing
// Loop through product attribute settings array
foreach ( $attributes_names as $attribute_name ) {
if ( $value = $product->get_attribute($attribute_name) ) {
$attributes_data[] = $attribute_name . ': ' . $value;
}
}
if ( ! empty($attributes_data) ) {
echo '<div class="items" style="color: red;"><p>' . implode( '<br>', $attributes_data ) . '</p></div>';
}
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。