仅在一个部分中运行wordpress查询


Only run wordpress query in one section

我目前有一个设置,其中我按顺序调用以下文件。

在我的标题.php中,我正在调用<?php get_theme_part( 'front', 'current-front' ); ?>

该文件的内容是

<?php query_posts("showposts=1&cat=6"); ?>
<?php
/**
 * The template for displaying list of recent posts on the front page.
 *
 * @package WordPress
 * @subpackage xxx
 * @since xxx 1.0
 */
if ( !have_posts() ) 
    return;
?>
<div class="front-current-print">
        <div class="current-print">
            <?php while ( have_posts() ) : the_post(); ?>
                <?php get_theme_part( 'current-print' ); ?>
            <?php endwhile; ?>
        </div>
</div>

该文件正在调用 current-print.php,其中包含以下代码:

<?php
?><article <?php post_class( 'compact bg-secondary' ); ?>>
    <a href="<?php the_permalink() ?>"><?php the_post_thumbnail( 'current-print' ); ?></a>
    <h5 class="title">
        <a class="inverse" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </h5>
    <div class="entry-summary"><?php the_excerpt(); ?></div>
    <?php the_post_episode(); ?>
</article>

此代码允许我拥有特定类别中特定帖子的缩略图。

这在首页上工作正常,但似乎对于所有内部页面和帖子,它只会显示类别和帖子。 我试过拿出<?php query_posts("showposts=1&cat=6"); ?>,帖子很好。 有什么方法可以让该脚本仅在标题中运行而不影响站点的其余部分?

你需要使用 wp_reset_query();

wp_reset_query() 将 $wp_query 和全局发布数据恢复到原始主查询。如果必须使用该函数,则应在 query_posts() 之后调用此函数。

请参阅:http://codex.wordpress.org/Function_Reference/wp_reset_query

在您的情况下,这将是:

<?php query_posts("showposts=1&cat=6"); ?>
<?php
/**
 * The template for displaying list of recent posts on the front page.
 *
 * @package WordPress
 * @subpackage xxx
 * @since xxx 1.0
 */
if ( !have_posts() ) 
    return;
?>
<div class="front-current-print">
        <div class="current-print">
            <?php while ( have_posts() ) : the_post(); ?>
                <?php get_theme_part( 'current-print' ); ?>
            <?php endwhile; ?>
        </div>
</div>
<?php wp_reset_query(); ?>