Skip to content

Instantly share code, notes, and snippets.

@trey8611
Last active April 17, 2024 17:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trey8611/41b6735acb5d67f6b7ca5857919bd5f8 to your computer and use it in GitHub Desktop.
Save trey8611/41b6735acb5d67f6b7ca5857919bd5f8 to your computer and use it in GitHub Desktop.
[Find WooCommerce Attributes by Name] Search by name instead of slug only. #wpallimport #woocommerce

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;
					}
				}				
			}
		}
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment