Find attributes by name.
function my_find_attribute_by_name( $name, $attribute ) {
global $wpdb;
$term_table = $wpdb->prefix . 'terms';
$taxonomy_table = $wpdb->prefix . 'term_taxonomy';
if ( ! empty( $name ) ) {
$query = "SELECT `slug` FROM `".$term_table."`";
$query .= " JOIN `".$taxonomy_table."` ON `".$term_table."`.`term_id` = `".$taxonomy_table."`.`term_id`";
$query .= " WHERE `name` = '".$name."' AND `taxonomy` = '".$attribute."'";
$result = $wpdb->get_row( $query );
if ( ! empty( $result ) ) {
return $result->slug;
}
}
}
Auto-create terms if they don't exist. This only works when the attribute itself already exists.
function my_find_attribute_by_name( $name, $attribute, $create = false ) {
global $wpdb;
$term_table = $wpdb->prefix . 'terms';
$taxonomy_table = $wpdb->prefix . 'term_taxonomy';
if ( ! empty( $name ) ) {
$query = "SELECT `slug` FROM `".$term_table."`";
$query .= " JOIN `".$taxonomy_table."` ON `".$term_table."`.`term_id` = `".$taxonomy_table."`.`term_id`";
$query .= " WHERE `name` = '".$name."' AND ( `taxonomy` = '".$attribute."' OR `taxonomy` = 'pa_" . $attribute . "' )";
$result = $wpdb->get_row( $query );
if ( ! empty( $result ) ) {
return $result->slug;
} else {
if ( $create == true ) {
if ( substr( $attribute, 0, 3 ) != 'pa_' ) {
$attribute = 'pa_' . $attribute;
}
if ( $term = wp_insert_term( $name, $attribute ) ) {
$term_data = get_term_by( 'id', $term['term_id'], $attribute );
if ( $term_data ) {
return $term_data->slug;
}
}
}
}
}
}