php - Get product attributes details in WooCommerce 3 -
in php developing "single product page" each field capture , display data retrieved database. stumbled upon 'product attributes' database field since has stored value:
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;}} that frankly don't know how manage in order extract values , replicate them on php dedicated field. looks json format. on how decoding information , report in php form?
you might use wp dedicated function maybe_unserialize() string serialized array:
$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 string $data_array = maybe_unserialize( $serialized_string ); // output test echo '<pre>'; print_r( $data_array ); echo '</pre>'; i this:
array ( [pa_flacone] => array ( [name] => pa_flacone [value] => [position] => 0 [is_visible] => 1 [is_variation] => 1 [is_taxonomy] => 1 ) ) but product metadata can unserialized, using get_post_meta() function:
set product id $product_id = 40; // data (last argument need on "false" serialized arrays) $attributes_array = get_post_meta( $product_id, '_product_attributes', false); // output test echo '<pre>'; print_r( $attributes_array ); echo '</pre>'; you same output.
to finish can data through wc_product object use available methods class:
// set product id $product_id = 40; // wc_product object $product = wc_get_product( $product_id ); // using wc_product method get_attributes() $product_attributes = $product->get_attributes(); // output test echo '<pre>'; print_r( $product_attributes ); echo '</pre>'; this time bit different. attributes data stored in wc_product_attribute objects , should need use available methods class in order access data as:
// set product id $product_id = 40; // 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 $attribute_taxonomy => $product_attribute){ // name (for example) $name = $product_attribute->get_name() // access data in array of values $attribute_data = $product_attribute->get_data(); }
Comments
Post a Comment