After hours and hours I can’t implement JavaScript code into PHP. JavaScript code is an ad code which I need to implement in WordPress, using functions.php, but every-time I get following error:
identifier "key", expecting ";" in your code
I am trying to create shortcode first and then to use that shortcode anywhere on site, including also injection through PHP, but also directly in content. NOTICE: JavaScript code can not be changed, thus – any customization of JavaScript code is not an option, but I am out of PHP solutions.
My code:
function jsad_code_shortcode() {
return '<script type="text/javascript">
atOptions = {
'key' : '9f8c74bccbdb424a067d31a8a20551a3',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://versatileadvancement.com/9f8c74bccbdb424a067d31a8a20221c6/invoke.js"></scr' + 'ipt>');
</script>';
}
add_shortcode( 'jsad_code', 'ad_code_shortcode' );
3
Answers
Solution is to use HEREDOC syntax, so the shortcode with this kind of JS should look like as follows:
Thank you all...
try this code.
Please don’t solve it by wrapping your code with HEREDOC syntax. The problem still is that you’re writing JavaScript in a PHP context, which should be avoided if possible.
Instead, write your data as a PHP array and encode it to JSON. Both JavaScript and PHP know how to interpret JSON. Use a combination of
wp_register_script
andwp_add_inline_script
to setup your script tags.After that the only thing that you have to do is to enqueue the script. This will place the script with the rest of the script tags in either the
<head>
or at the closing</body>
tag, depending on your settings. This will also ensure that the script is only printed to the screen once.