php - 在 WooCommerce 3 中获取产品属性详细信息

标签 php mysql wordpress serialization woocommerce

在 php 中,我正在开发一个“单一产品页面”,其中每个字段捕获并显示从数据库检索的数据。我偶然发现了“产品属性”数据库字段,因为它存储了这个值:

a:1:{s:10:"pa_flacone";a:6:{s:4:"name";s:10:"pa_flacone";s:5:"value";s:0:"";s:8:"position";s:1:"0";s:10:"is_visible";s:1:"1";s:12:"is_variation";i:1;s:11:"is_taxonomy";i:1;}}

坦率地说,我不知道如何管理以提取值并将它们复制到 php 专用字段上。看起来像Json格式。有关如何解码此信息并以 php 形式报告的任何帮助吗?

最佳答案

您可以使用WP专用功能maybe_unserialize()因为您的字符串是序列化数组:

$serialized_string = 'a:1:{s:10:"pa_flacone";a:6:{s:4:"name";s:10:"pa_flacone";s:5:"value";s:0:"";s:8:"position";s:1:"0";s:10:"is_visible";s:1:"1";s:12:"is_variation";i:1;s:11:"is_taxonomy";i:1;}}';

// Unserializing this string
$data_array = maybe_unserialize( $serialized_string );

// Output for test
echo '<pre>'; print_r( $data_array ); echo '</pre>'; 

我会得到这个:

Array
(
    [pa_flacone] => Array
        (
            [name] => pa_flacone
            [value] => 
            [position] => 0
            [is_visible] => 1
            [is_variation] => 1
            [is_taxonomy] => 1
        )

)

但这是一些产品元数据,您可以使用 get_post_meta() 对其进行反序列化。功能:

Set your product ID
$product_id = 40;

// Get the data (last argument need to be on "false" for serialized arrays)
$attributes_array = get_post_meta( $product_id, '_product_attributes', false); 

// Output for test
echo '<pre>'; print_r( $attributes_array ); echo '</pre>';  

您将得到相同的输出。


最后,您可以通过 WC_Product 获取此数据。对象使用此类的所有可用方法:

// Set your product ID
$product_id = 40;

// Get the WC_Product object
$product = wc_get_product( $product_id );

// Using WC_Product method get_attributes()
$product_attributes = $product->get_attributes();

// Output for test
echo '<pre>'; print_r( $product_attributes ); echo '</pre>'; 

这一次你会得到一些不同的东西。所有属性数据都存储在 WC_Product_Attribute 中对象,您应该需要使用此类的可用方法才能访问数据,如下所示:

// Set your product ID
$product_id = 40;

// Get the WC_Product object
$product = wc_get_product( $product_id );

// Using WC_Product method get_attributes()
$product_attributes = $product->get_attributes();

// Iterating through each WC_Product_attribute object
foreach( $product_attributes as $attribute_taxonomy => $product_attribute){

    // get the name (for example)
    $name = $product_attribute->get_name()

    // Access to the data in an array of values
    $attribute_data = $product_attribute->get_data();
}

关于php - 在 WooCommerce 3 中获取产品属性详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45695438/

相关文章:

php - 为什么我应该使用/不使用可空字段 Laravel - MySQL

php - Python 的 locals() 的 PHP 等价物是什么?

mysql - 如果不存在则插入,否则更新同一查询中的两个表

java - 如何将 null 发送到整数字段 - JAVA REST

jQuery如何通过下拉列表过滤内容

css - 制作一个带有 map 响应的 wordpress 页面

php - Woocommerce API 回调不接受 POST 参数

php - simplepie 不解析 google 新闻 rss feed

javascript - 查看view-source :时如何加载不同的代码

mysql - 在 MySQL 中,如何删除/刷新/清除所有不需要的日志?