I am trying to retrieve a list of all my attributes_name
values (carat, color, size etc) from the WooCommerce table wp_woocommerce_attribute_taxonomies
in WordPress database.
And here is my code from the below but getting the name of the attribute and not what’s inside that column:
$sql = "SELECT attribute_name FROM wp_woocommerce_attribute_taxonomies";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['attribute_name'] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
Any idea how to retrieve whats inside them?
global $wpdb;
$results = $wpdb->get_results( "
SELECT attribute_name
FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
" );
if ( count($results) > 0) {
$data = []; // Initializing
// Loop through results objects
foreach( $results as $result ) {
// add each value to an array
$data[] = $result->attribute_name . "<br>";
}
// output data of all rows
echo implode( "<br>", $data );
} else {
echo "0 results";
}
Better, when you are querying one column of a table (as you are doing), you can use get_col()
method this way:
global $wpdb;
$results = $wpdb->get_col( "
SELECT attribute_name
FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
" );
if ( count($results) > 0) {
// output data of all rows
echo implode( "<br>", $results );
} else {
echo "0 results";
}
The best easy way is to use WooCommerce wc_get_attribute_taxonomies()
dedicated function:
$output="<ul style="list-style:none;">";
// Loop through all Woocommerce product attributes
foreach( wc_get_attribute_taxonomies() as $attribute ) {
$attribute_label = $attribute->attribute_label; // Product attribute name
$attribute_slug = $attribute->attribute_name; // Product attribute slug
$output .= '<li class="'.$attribute_slug.'">' . $attribute_label . '</li>';
}
// Output
echo $output . '</ul>';
Related thread: Get woocommerce product attributes to sidebar