Home > Mobile >  Syntax error in WordPress shortcode PHP file
Syntax error in WordPress shortcode PHP file

Time:10-18

I am trying to register a WordPress shortcode.

I have a PHP return statement that includes HTML. Inside the HTML, I have a javascript onclick function. Visual Studio Code is throwing a syntax error which is, unexpected 'frame' (T_STRING), expecting ',' or ';'

I have read other articles on Stack Overflow and I have tried escaping single quotes that are inside the string but I could be inaccurately escaping. Below is some raw code without any escaping.

I understand the code below may not be pretty, but all help is appreciated nonetheless.

<?php
function torque_hello_world_shortcode() {
return '<div ></div>
<a onclick="document.getElementById('frame').style.display = document.getElementById('frame').style.display == 'none' ? 'block' : 'none'; return false;"><img  src="#" alt="alt text" style="width:60px;height:60px;cursor:pointer !important;">
    <p  style="cursor:pointer !important;">text! <span  style="cursor:pointer !important;">more text</span></p></a>
<div ></div>';
 }

add_shortcode( 'helloworld', 'torque_hello_world_shortcode' );

CodePudding user response:

You're mixing single and double quotes in your return statement (on line 2 of the string, you basically close the string and follow it with the word "frame", without using concatenation or even the $ variable sign).

If you open a string with single quotes, a second single quote will close the string. If you need to use single quotes within your string, you need to escape it, with a backslash: echo 'Arnold once said: "I\'ll be back"';
I added backslashes to your code:

<?php
function torque_hello_world_shortcode() {
  return '<div ></div>
    <a onclick="document.getElementById(\'frame\').style.display = 
    document.getElementById(\'frame\').style.display == \'none\' ? \'block\' : 
    \'none\'; return false;"><img  src="#" alt="alt text" 
    style="width:60px;height:60px;cursor:pointer !important;">
    <p  style="cursor:pointer !important;">text! <span 
     style="cursor:pointer !important;">more text</span></p></a>
    <iframe id="frame" src="#"  allowfullscreen="" frameborder="0"> 
    </iframe> 
    <div ></div>';
  }

add_shortcode( 'helloworld', 'torque_hello_world_shortcode' );
  • Related