I am a frontend getting into backend, so for me this is totally new. So I am experimenting with ACF custom fields in Wordpress, and wanted to build my own simple "code" field(just in case, please, do not suggest another because I already tried one and I had conflicts with other libraries so that's why I decided to go and build it myself, and mainly they are out to day), in the frontend I am using twig and prism to get the things highlighted that works fine, but then in my backend (the important part) I have a custom field that receive the code, which is a "textarea", but put attention to me explanation first, and I have another one, called languages so I can filter the languages to display in the frontend mainly to highlight properly by rendering the right class, everything fine with it. BUT I realized when I have HTML, the value is rendering by the browser as html, with that being said I meant, instead of:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>

I am getting:

My first Heading My first paragraph

Now, just to clarify, I read about text areas having troubles with HTML and rendering strings instead so I made a test and in my custom ACF field I used (just for test) a div with contenteditable= "true" and it worked the same, which means is not a direct problem with the textarea. So I also tested in the backend to print the value so:

echo '<pre>'
print_r($field[value])
echo '</pre>'

and I always get the HTML rendered, now ...I also tried to parse the value inside two php functions which are htmlspecialchars() and the other one was html_entity_decode() but I am always having the same issue.

Also just to clarify in the frontend I have :

{% set bem = bem | extenBem('code-editor', alias) %}

{% block template %}
<pre class="{{ bem.classString }}">
<code>
{{ code }}
</code>
</pre>
{% endblock %}

In my ACF rendered function in the backend I have...

public function render_field($field){
  <textarea>
    name="<?php echo esc_atr($field['name']) ?>"
    <?php echo print_r($field['value']) ?>
  </texarea>
}

Please take into consideration what I mentioned before, what I tried or how I tried to parse the variable, so not just with print_r or echo.

An advice will be really appreciate and thank you in advice for reading.

1

There are 1 answers

1
TSCAmerica.com On

I updated the code to use the esc_textarea function that will convert HTML characters to their respective HTML entities, so they are displayed as text rather than being rendered as HTML by the browser. Hope that helps!

public function render_field($field) {
  ?>
  <textarea name="<?php echo esc_attr($field['name']); ?>">
    <?php echo esc_textarea($field['value']); ?>
  </textarea>
  <?php
}