skip to Main Content

Sorry I’m quite new at coding, and also working with WordPress and ACF, and I’m trying my best but I can’t figure this out:

I’m trying to load my taxonomy description in rich text.
Currently I’m using this code:

<?php
$terms = get_the_terms(get_the_ID(), 'locatie'); // Get the terms associated with the post
if ($terms && !is_wp_error($terms)) :
    foreach ($terms as $term) : ?>
        <h2><?php echo ($term->name); ?></h2>
        <p><?php echo ($term->description); ?></p>
    <?php endforeach;
endif;
?>

I want to put in location information, add some line breaks, maybe use HTML, and add a link to Google Maps or something. I downloaded a plugin to enable a rich text editing within the taxonomy, and formatted it correctly. However, the code return is without all the formatting. How can I make sure that the formatted, rich text/html description is loaded?

Any suggestions are more then welcome <3

2

Answers


  1. Chosen as BEST ANSWER



    So after some coding, and some testing and stuff I finally got it working. I noticed that the Term description was being stored in the database as escaped HTML entities (<br>), which means WordPress is storing the <br> tags as text, not as actual HTML.

    So I wrote some code to decode the HTML entities to actual bring back the proper <br> tags!

    <?php
    // Temporarily remove all filters on term_description
    remove_all_filters('term_description');
    
    // Get terms associated with the post
    $terms = get_the_terms(get_the_ID(), 'locatie'); 
    if ($terms && !is_wp_error($terms)) :
        foreach ($terms as $term) :
            // Decode HTML entities to get actual <br> tags
            $decoded_description = html_entity_decode($term->description);
            ?>
            <p>
                <b><?php echo esc_html($term->name); ?></b><br>
                <?php echo wp_kses_post($decoded_description); ?><br>
                <?php echo esc_html($term->adresveld); ?>
            </p>
        <?php endforeach;
    endif;
    
    // Re-add the filters for term_description if needed
    add_filter('term_description', 'wpautop');
    ?>
    

  2. I think what’s holding you down there is that esc_html(...) function.
    It exactly counteracts what you want to achieve.

    You want the raw, non-escaped version of your string value. I assume that what your ‘description’ field returns looks something like this <p>Hello world!</p><br>.
    What esc_html does with that is called "escaping". Which would be replacing all the special characters that browsers interpret as HTML, such as replacing < and > with &lt; and &gt; respectively.

    I assume if you replace the line with the following it should work:

    <?php echo $term->description; ?>
    

    You can learn more about when and how to use this function here: https://developer.wordpress.org/reference/functions/esc_html/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search