使用WordPress进行自定义SQL查询时,应始终使用WPDB
类和相关方法get_results()
, 这样做:
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, 当您查询表的一列时(正如您所做的),您可以使用
get_col()
方法如下:
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 就是使用WooCommerce
wc_get_attribute_taxonomies()
专用功能:
$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>\';
相关线程:
Get woocommerce product attributes to sidebar