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

后端 未结 4 1848
野趣味
野趣味 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:51

    As I struggled with the same issue I have tried using the code from Jesus Magallon. However, it did not work.

    I found out that the priority of wp_ajax_woocommerce_save_attributes needed to be set to 0, otherwise the callback is not run for some reason.

    Forthermore, if we only use $post->ID for get_post_meta() the correct results state of the checkbox will only be visible on page reload. To make sure the selected state is also visible direclty after ajax saving/reloading, we need to use $post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : $post->ID; instead.

    Here the final version that should work perfectly for everyone:

    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', 0);
    
    function get_attribute_highlighted( $attribute_name, $i ) {
        global $post;
    
        // ID for either from ajax or from post
        $post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : $post->ID ;
        $attribute_name = strtolower( sanitize_title( $attribute_name ) );
        $val = get_post_meta( $post_id, 'attribute_' . $attribute_name . '_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_' . absint( $i ), wc_string_to_bool( $val ) ); } } }

提交回复
热议问题