How can I save a custom field of an attribute in Woocommerce?

后端 未结 4 1841
野趣味
野趣味 2021-01-26 07:21

Old

I am trying to create a custom field in the product attributes in Woocommerce. This to be able to select if an attribute is highlighted or not. For example:

4条回答
  •  时光说笑
    2021-01-26 07:37

    Check Ink's answer


    Outdated

    I have found the solution to my problem. I share the code in case someone is useful. Regards!

    add_action('woocommerce_after_product_attribute_settings', 'wcb_add_product_attribute_is_highlighted', 10, 2);
    add_action('wp_ajax_woocommerce_save_attributes', 'wcb_ajax_woocommerce_save_attributes', 10);
    
    function get_attribute_highlighted($id, $i) {
        global $post;
        $id = sanitize_title($id);
        $id = strtolower($id);
        $val = get_post_meta( $post->ID, "attribute_".$id."_highlighted_".$i, true);
        return !empty($val) ? $val : false;
    }
    
    function wcb_add_product_attribute_is_highlighted($attribute, $i=0) {
        $value = get_attribute_highlighted($attribute->get_name(), $i); ?>
            
                
                    
    $val) { $attr_name = sanitize_title($data["attribute_names"][$i]); $attr_name = strtolower($attr_name); update_post_meta( $post_id, "attribute_".$attr_name."_highlighted_".$i, wc_string_to_bool($val) ); } } }

    In the end the only thing I had to add to my code was a hidden input with the same name as the checkbox but with a value of 0:

    Here an image of the result (https://i.stack.imgur.com/VscT1.jpg). By clicking on save the value of the checkbox is maintained. The value is saved in a post_meta of the post that you are modifying. This is useful if you want to highlight a specific attribute in the front end.

    I appreciate the help of @LoicTheAztec :)

提交回复
热议问题