get_posts在一个WP静态页面


get_posts on a WP static page

这是我第一次在论坛上提问。我希望我能说得足够具体。我试图取代一个WP模板的首页帖子部分。当WP主题设置为设置>阅读>您的最新帖子时,我有下面的代码在我的index.php页面上运行良好(它获得帖子),但是WP主题"思考者"设置阅读的方式设置为静态页面,帖子通过博客模板页面(与index.php文件位于同一位置)获得,该页面从循环中分别包含的文件中获取帖子。出于几个原因,我希望将其设置为静态。我的问题是"是否有一个原因,为什么下面的代码只工作在一个index.php文件,而不是一个博客模板文件,这是在同一位置的index.php文件。我已经检查过了,代码中调用的模板部分正在被调用。似乎没有帖子可以获取(有)。

感谢您的宝贵时间,

戴夫

<!-- blog content -->
    <div class="container">
        <div class="row" id="primary">
            <main id="content" class="col-sm-8" role="main">
                <?php if ( have_posts() ) : ?>

                <?php /* Start the Loop */ ?>
                <?php while ( have_posts() ) : the_post(); ?>
                    <?php
                        get_template_part( 'template-parts/content', get_post_format() );
                    ?>
                <?php endwhile; ?>
                <?php the_posts_navigation(); ?> 
                <?php else : ?>
                    <?php get_template_part( 'template-parts/content', 'none' ); ?>
                <?php endif; ?>
        </main><!-- content -->

        <!-- sidebar -->
        <aside class="col-sm-4">
            <?php get_sidebar(); ?>
        </aside>
    </div><!-- primary -->
</div><!-- container -->

have_posts()函数只允许您检查页面是否有帖子,因为它是您的静态页面,不会有帖子分配给该页。

您需要在页面开始处首先查询以显示帖子。以下是示例。

编辑::

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'movie_genre',
            'field'    => 'slug',
            'terms'    => array( 'action', 'comedy' ),
        ),
        array(
            'taxonomy' => 'actor',
            'field'    => 'term_id',
            'terms'    => array( 103, 115, 206 ),
            'operator' => 'NOT IN',
        ),
    ),
);
$query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
    <!-- pagination here -->
    <!-- the loop -->
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><?php the_title(); ?></h2>
    <?php endwhile; ?>
    <!-- end of the loop -->
    <!-- pagination here -->
    <?php wp_reset_postdata(); ?>
<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

您可以在下面的链接中找到更多关于WP_Query的信息