admin管理员组

文章数量:1125105

My posts have Custom Fields, one of which includes code snippets. I tried esc_html() to present them on the site. this is what I do:

$code = get_post_meta(get_the_id(),'code_snippet')[0];
$code_html = esc_html($code);
echo $code_html;

This doesn't work. It prints the code but whenever there are <or > it interprets it as HTML and collapses everything in between as if it was a tag.

However, if I copy the same text from the Custom Field in the dashboard and paste it into the code (so assign $code the pasted string) it does work. And I don't understand why.

Edit: ✅ Solved! It seems like get_post_meta() is returning an already "stripped" string. I changed how I get the custom field content to

$code = get_post_custom_values($key = 'code_snippet');
echo esc_html($code[0]);

and now it is working.

本文标签: escapingeschtml don39t work on variable but do work on pasted text