Support » Developing with WordPress » Custom Field HTML formatting

  • toolsnz

    (@toolsnz)


    I am using a custom field for an alternative out of stock message for products.
    I obviously want a visible message to the user, but would also like to do some html formatting such as a “… Learn more” link.
    But all html formatting is stripped out. I think at the time of saving.

    Should the field be of a different type to allow and save HTML formatting?

    /**
     * Display the custom text field
     * @since 1.0.0
     * custom text field for An alternative out of stock text
     * Displayed in Product -> Inventory
     */
    function cfwc_create_custom_field() {
     $args = array(
     'id' => 'AltOutOfStockText',
     'label' => __( 'Alt Out of Stock Notice', 'cfwc' ),
     'class' => 'cfwc-custom-field',
     'desc_tip' => true,
     'description' => __( 'Alternative Text displayed when out of stock. Displayed when out of stock. Use when closing bookings and displaying the text out of stock is not desirable. Leave empty if store default "out of stock" is desired', 'ctwc' ),
     );
     woocommerce_wp_text_input( $args );
    }
    add_action( 'woocommerce_product_options_inventory_product_data', 'cfwc_create_custom_field' );
    /**
     * Save the custom field
     * @since 1.0.0
     * custom text field for An alternative out of stock text
     * Displayed in Product -> Inventory
     */
    function cfwc_save_custom_field( $post_id ) {
     $product = wc_get_product( $post_id );
     $title = isset( $_POST['AltOutOfStockText'] ) ? $_POST['AltOutOfStockText'] : '';
     $product->update_meta_data( 'AltOutOfStockText', sanitize_text_field( $title ) );
     $product->save();
    }
    add_action( 'woocommerce_process_product_meta', 'cfwc_save_custom_field' );
    
    // Custom out of stock message, from custom product field
    // Product field = 'AltOutOfStockText'
    add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2);
    function wcs_custom_get_availability( $availability, $_product ) {
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    sanitize_text_field() will strip out HTML tags. If you want to save HTML you need a less aggressive sanitation. Maybe wp_kses_post() perhaps? Or you could create a custom array of allowed HTML and use wp_kses() instead. I can’t tell you the optimal sanitation, it depends on the sort of data you are getting and how well the user has been vetted.

    The $product->update_meta_data() could also be doing sanitation of its own. Consult with WC docs, code, or support for more information on this method.

    toolsnz

    (@toolsnz)

    Thanks very much, wp_kses_post() worked for me and allows basic html formatting to be saved in the custom field

    Moderator bcworkz

    (@bcworkz)

    Cool! You’re welcome.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.