0

I'm working on this project where I want to add some html on my wordpress website. The point is to add a "read more" button. Here's the code:

<p>some text<span id="dots">...</span><span id="more">Some more text.</span></p>
<button onclick="myFunction()" id="myBtn">Read more</button>

<style>
  #more {display: none;}
</style>

<script type="text/javascript">
  function myFunction() {
    var dots = document.getElementById("dots");
    var moreText = document.getElementById("more");
    var btnText = document.getElementById("myBtn");

    if (dots.style.display === "none") {
      dots.style.display = "inline";
      btnText.innerHTML = "Read more";
      moreText.style.display = "none";
    } else {
      dots.style.display = "none";
      btnText.innerHTML = "Read less";
      moreText.style.display = "inline";
    }
  }
</script>

Here's the result:

Read more #more {display: none;} function myFunction() { var dots = document.getElementById(“dots”); var moreText = document.getElementById(“more”); var btnText = document.getElementById(“myBtn”); if (dots.style.display === “none”) { dots.style.display = “inline”; btnText.innerHTML = “Read more”; moreText.style.display = “none”; } else { dots.style.display = “none”; btnText.innerHTML = “Read less”; moreText.style.display = “inline”; } } 

My issue: the wordpress reads the and processes the html, but spits back the javascript (exactly as stated above).

Please help

1
  • 1
    Where/how did you add this code? Commented Jan 29 at 2:58

2 Answers 2

1

The script tags are only there to contain the JavaScript that will be executed by the browser. You need to tell WordPress to ignore those tags so it doesn't process them as HTML. One way to do this is to use the "esc_html" function. You'll need to wrap the script tags in the following code:

<?php echo esc_html( '<script type="text/javascript">' . $script . '</script
0

You can use a plugin to add the code where you need it. Instead of the javascript you show above you add a shortcode that makes your javascript show on the page as expected.

I use a plugin called WPCode and it let's you add javascript code and css code as needed.

Here is how I do it:

Step 1: Click new snippet and choose "add your own code snippet"

Step 2: add my javascript in the snippet box and choose "javascript" from the dropdown menu in the right of the page

Step 3: Choose "shortcode" from the insert method (it will want you to save you snippet first). Then let it create my unique shortcode tag

Step 4: Add the shortcode with your code in the content editor like this: [my_short_code]

You can do all this with the free version or upgrade for more features.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.