首页 > 解决方案 > WordPress 添加


如果我不在循环中使用 wp_reset_postdata()和标签。为什么?

问题描述

我有一个用于自定义帖子类型数据的简单 WordPress WP 查询循环。由于使用 FacetWP 过滤数据,我必须删除wp_reset_postdata(). 否则 ajax 过滤不起作用。

但如果我删除,WordPress 会在我的 HTML 内容wp_reset_postdata()中添加很多p和标签。br为什么?

我的代码:

// 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
  }

}

如果我不使用 重置 postdata,p您知道为什么 WordPress 会添加很多标签吗?brwp_reset_postdata()

标签: wordpressfacetwp

解决方案


wp_reset_postdata因为对成型没有影响the_content

在循环一个单独的查询之后,这个函数将$post全局恢复到主查询中的当前帖子。

当您输出内容时,在循环中,您可以清理输出以删除所有使用wp_strip_all_tags.

正确剥离所有 HTML 标记,包括脚本和样式。

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

truefalse换行)。

或者,您可以通过删除文件中的通孔<p>来删除作为换行符应用的任何自动标记。wpautopremove_filterfunction.php

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

推荐阅读