skip to Main Content

I have an attribute:

  • Name(label): Box Size
  • Slag: box-size

I tried this code:

$attribute_slug = 'pa_box-size'; 

// Get the term object based on the attribute slug
$term = get_term_by('slug', $attribute_slug, 'pa');

if ($term) {
   $attribute_label = $term->name; // Attribute label
   $attribute_id = $term->term_id; // Attribute ID

   // Output the attribute label and ID
   echo 'Attribute Slug: ' . $attribute_slug . '<br>';
   echo 'Attribute Label: ' . $attribute_label . '<br>';
   echo 'Attribute ID: ' . $attribute_id;
} else {
   echo 'Attribute not found: ' . $attribute_slug;
}

But got always "Attribute not found: pa_box-size".

2

Answers


  1. Chosen as BEST ANSWER

    I solved my problem with this:

    $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
      $attribute_id = $attribute->attribute_id;        // Attribute ID
    
      $output.= '<li class="'.$attribute_slug.'" data-id="'.$attribute_id.'">'
                    .$attribute_label.'</li>';
    }
    // Output
    echo $output.'</ul>';
    

    Source: wordpress.stackexchange.com

    So I will just need an IF statement to check a specific attribute.


  2. You can try this code.
    
    $attribute_slug = 'color'; // Replace with your attribute slug
    
    $product_attributes = wc_get_attribute_taxonomies();
    
    foreach ($product_attributes as $product_attribute) {
        if ($product_attribute->attribute_name === $attribute_slug) {
            $attribute_label = $product_attribute->attribute_label;
            $attribute_id = $product_attribute->attribute_id;
    
            echo 'Attribute Label: ' . $attribute_label . '<br>';
            echo 'Attribute ID: ' . $attribute_id;
    
            break;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search