• Resolved Nilambar Sharma

    (@rabmalin)


    I was looking for sanitizing HEX color value. I found function sanitize_hex_color and it is included in class-wp-customize-manager.php. Why is that function kept in there? I am trying to use it in my theme but it says function not found.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Ryan

    (@ryanmclaughlin1)

    Nilambar –

    I imagine this function is kept there because it is probably only used in core by the customizer.

    And the reason it is saying function not found is that this file is not included with every page request – only when you are actually in the customizer.

    The actual function is small and simple, so an easy fix would be to duplicate it in your theme/plugin wrapped in a function_exists check. This way it will always be available to you.

    So like this:

    if ( ! function_exists( 'sanitize_hex_color' ) ) {
        function sanitize_hex_color( $color ) {
            if ( '' === $color )
                return '';
    
            // 3 or 6 hex digits, or the empty string.
            if ( preg_match('|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) )
                return $color;
    
            return null;
        }
    }
    Dion

    (@diondesigns)

    If such a function is going to be added to a theme/plugin, it should not have the same name as a WordPress-supplied function. The class-wp-customize-manager.php file is not loaded in wp-settings.php, so it is possible the file would be loaded after the new function is defined in the theme/plugin. That would generate a fatal PHP error.

    The following line of code could replace the function:

    $color = (empty($color) || !preg_match('|^#([A-Fa-f0-9]{3}){1,2}$|', $color)) ? '' : $color;

    Ryan

    (@ryanmclaughlin1)

    Yes you are absolutely right. I made some assumptions about load order in my first response but after taking a closer look class-wp-customize-manager.php isn’t included until the plugins_loaded hook. I will edit my previous to reflect this.

    edit: i guess i can’t edit old posts, so nevermind.

    Thread Starter Nilambar Sharma

    (@rabmalin)

    Marking as resolved.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘About sanitizing hex color [sanitize_hex_color]’ is closed to new replies.