0

A function in one of php files of a WordPress-based website is cut off, I think due to an error in escaping multiple quotes and slashes.

Here's the line of code in question:

echo '<script>window.jQuery || document.write(\'<script src="' . get_template_directory_uri() . '/assets/js/vendor/jquery-1.11.0.min.js"><\/script>\')</script>' . "\n";

It generates the following html:

<script>window.jQuery || document.write('

Everything else after the ' is not displayed and doesn't execute.

As a temporary solution, I inserted the closing <!-- my hack --> </script> tag straight into html page.

This resulted in the following html output:

<script>window.jQuery || document.write('<script type='text/javascript' src='/wp-content/themes/my-theme/assets/js/vendor/modernizr-2.7.0.min.js'></script><!-- my hack --></script>

Not seeing any errors, could someone please help? Here's the entire function:

function roots_jquery_local_fallback($src, $handle = null) {
  static $add_jquery_fallback = false;
  if ($add_jquery_fallback) {

    echo '<script>window.jQuery || document.write(\'<script src="' . get_template_directory_uri() . '/assets/vendor/jquery/dist/jquery.min.js?1.11.1"><\/script>\')</script>' . "\n";

    $add_jquery_fallback = false;
  }
  if ($handle === 'jquery') {
    $add_jquery_fallback = true;
  }
  return $src;
}
add_action('wp_head', 'roots_jquery_local_fallback');

1 Answer 1

2

PHP does not example the text inside strings delimited by single quotes ('), so \' does not work. It does interpret inside double quotes("), so reverse your use of single and double and use \".

echo "<script>window.jQuery || document.write('<script src=\"" . get_template_directory_uri() . "/assets/js/vendor/jquery-1.11.0.min.js\"><\/script>\')</script>" . "\n";
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant! Thank you, @bobdye! Solved the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.