Home Forums Basel support forum Add Attribute Programmatically, But Product not Shown on Widget Filter

Add Attribute Programmatically, But Product not Shown on Widget Filter

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #523843

    playingryan
    Participant

    Hi,
    I’m successfully add attribute programmatically, the attribute shown on admin side.
    But when I try to filter on front end, the product not shown.

    https://prnt.sc/csxsrLW0AAk3

    Do I need to clear cache or something?

    This is my code:

    $attribute_name = 'pa_color';
    $product_id = $product->get_id();
    $colours = array('Black', 'Blue', 'Brown');
    
    $new_attribute = array();
    $product_attributes = get_post_meta( $product_id, '_product_attributes', true );
    
    if ( ! empty( $colours ) ) {
        foreach( $colours as $color ) {
            $term = get_term_by( 'name', $color, $attribute_name );
                                    
            if ( $term && ! is_wp_error( $term ) ) {
                $insert = wp_set_object_terms( $product_id, $term->term_id, $attribute_name, true );
    
                if ( $insert ) {
                    // Append the new attribute values
                    $new_attribute = array(
                        $attribute_name => array(
                            'name'         => $attribute_name,
                            'value'        => '',
                            'position'     => 0,
                            'is_visible'   => 0,
                            'is_variation' => 0,
                            'is_taxonomy'  => 1,
                        ),
                    );
    
                    WP_CLI::success( 'Insert term: ' . $color );
                }
            }
        }
    }
    
    if ( is_array( $product_attributes ) ) {
        $product_attributes = array_merge( $product_attributes, $new_attribute );
    } else {
        $product_attributes = $new_attribute;
    }
    
    // Update the product with the modified attributes
    update_post_meta( $product_id, '_product_attributes', $product_attributes );
    • This topic was modified 2 months, 1 week ago by playingryan.
    • This topic was modified 2 months, 1 week ago by playingryan.
    #523946

    Artem Temos
    Keymaster

    Hello,

    Try to regenerate all lookup tables in WooCommerce -> Tools. It should help. Let me know if it works.

    Kind Regards

Viewing 2 posts - 1 through 2 (of 2 total)