【问题标题】:get_posts on a WP static pageWP 静态页面上的 get_posts
【发布时间】:2015-09-16 02:44:28
【问题描述】:

这是我第一次在这个论坛上提问。我希望我可以足够具体。我正在尝试替换 WP 模板的首页帖子部分。当 WP 主题设置为设置>阅读>您的最新帖子但 WP 主题“思想家”设置阅读的方式设置为静态时,我的 index.php 页面上的以下代码运行良好(它获取帖子)页面和帖子是通过博客模板页面(与 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 -->

【问题讨论】:

    标签: php wordpress static posts


    【解决方案1】:

    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 的更多信息。

    【讨论】:

    • 你基本上应该never use query_posts()...
    • 是的.. 已编辑。对不起。我在 wordpress 上工作的时间不长,所以我认为我使用的是 query_post()。谢谢你的提醒。 :)
    • 谢谢!这是有道理的:)
    • 很高兴知道我可以帮助你:)
    猜你喜欢
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多