• Hey guys. I’m getting this error in the following lines:

    Function WP_Scripts::localize was called incorrectly. The $l10n parameter must be an array. To pass arbitrary data to scripts, use the wp_add_inline_script() function instead:

    wp_localize_script( 'snax-front', 'snax_front_config', wp_json_encode( $front_config ) );
    wp_localize_script( 'snax-shares', 'snax_shares_config', wp_json_encode( $config ) );
    wp_localize_script( 'snax-collections', 'snax_collections_js_config', wp_json_encode( $config ) );
    

    Can someone help me, please?

    Thank you in advance.

Viewing 6 replies - 1 through 6 (of 6 total)
  • https://developer.www.ads-software.com/reference/functions/wp_localize_script/ requires an array as the 3rd parameter. However, you pass a string through the output of wp_json_encode(). Therefore, omit wp_json_encode() – then it should fit, provided the array contains the relevant information.

    Thread Starter Divvy

    (@divvy)

    Thank you for your response and for trying to help me.

    Do you mean like this?

    wp_localize_script( ‘snax-front’, ‘snax_front_config’, $front_config);
    wp_localize_script( ‘snax-shares’, ‘snax_shares_config’, $config);
    wp_localize_script(‘snax-collections’, ‘snax_collections_js_config’, $config);



    • This reply was modified 10 months, 3 weeks ago by Divvy.
    • This reply was modified 10 months, 3 weeks ago by Divvy.

    Yes, that’s exactly what I meant.

    Thread Starter Divvy

    (@divvy)

    The errors disappeared, but unfortunately, I get a new error:

    Uncaught SyntaxError: "[object Object]" is not valid JSON
    at parse ()
    at Function. (jquery-migrate.min.js?ver=3.4.1:2:3161)
    at e. as parseJSON
    at front.js?ver=1.13.6:26:20
    at front.js?ver=1.13.6:100:3


    Line 26:
    ctx.config = $.parseJSON(window.snax_front_config);

    Line 100:
    })(jQuery, snax);

    The file full code:
    https://paste2.org/m3stVCVs

    This is now a JavaScript error to which I cannot recognise the connection to your PHP code. My guess would be that $front_config and $config are not an array but an object. Take a closer look by debugging with var_dump(). Example:

    var_dump($front_config);exit;

    directly before the first line with wp_localise_script(). Then you should be able to recognise what the variable is when loading the page. As I said, it must be an array – not an object or a string.

    Thread Starter Divvy

    (@divvy)

    Thank you, my friend!

    I tried to ask chatgpt for help and he suggested to replace this line:

    ctx.config = $.parseJSON(window.snax_front_config);

    With:

    ctx.config = (typeof window.snax_front_config === 'string') ? $.parseJSON(window.snax_front_config) : window.snax_front_config;

    And seems to work so far ??

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘The $l10n parameter must be an array’ is closed to new replies.