WordPress adds <p> and <br> tags if I don't use wp_reset_postdata() in loop. Why?

110 Views Asked by At

I have a simple WordPress WP Query loop for custom post type data. Because of filtering the data with FacetWP I have to remove wp_reset_postdata(). Otherwise the ajax filtering is not working.

But if I remove wp_reset_postdata(), WordPress adds a lot of p and br tags to my HTML content. Why?

My code:

// WP_Query args
$args = array(
    'posts_per_page' => 20,
    'order' => 'ASC',
    'orderby' => 'title',
    'ignore_sticky_posts' => true,
    'post_type' => 'abc',
    'facetwp' => true
  );

  // The Query
  $abc_query = new \WP_Query($args);
  
  // The Loop
  if ( $abc_query->have_posts() ) {
    while ( $abc_query->have_posts() ) {
      $abc_query->the_post();
      ?>

      <div id="abc-wrapper">
      
      <ul class="abc-list">
        <li class="abc-list-elem">
            <h4 class="abc-title">
                <?php the_title(); ?>
            </h4>
            <span class="abc-desc">
                <?php the_content(); ?>
            </span>
            <?php 
                $terms = get_the_terms(get_the_ID(), 'abc_types');
                foreach($terms as $t) {
                    ?>
                        <span class="abc-badge">
                            <?php echo $t->name ?>
                        </span>
                    <?php
                }
            ?>
        </li>
      </ul>
      </div>



      <?php
    }
  } else {
    // There are no posts
  }

}

Do you have an idea why WordPress adds a lot of p and br tags if I don't reset the postdata with wp_reset_postdata()?

1

There are 1 best solutions below

0
amarinediary On

wp_reset_postdata as no impact on the_content formating.

After looping through a separate query, this function restores the $post global to the current post in the main query.

When you output the content, while in a loop, you can sanitize the output to remove any and all tags using wp_strip_all_tags.

Properly strip all HTML tags including script and style.

<?php wp_strip_all_tags( the_content(), true ); ?>

(true or false for line breaks).

Alternatively, you can remove any auto <p> tag applied as line break by removing the wpautop via remove_filter in your function.php file.

<?php remove_filter( 'the_content', 'wpautop' ); ?>