【问题标题】:Querying only the latest sticky post只查询最新置顶帖
【发布时间】:2015-10-21 16:23:19
【问题描述】:

所以我试图只从 WordPress 中提取最新的置顶帖子,并且只有 1 个。我使用的是“showpost=1”,但由于某种原因,如果我有两个被标记为置顶的帖子都出现了?

            <h2>Breaking News</h2>
    <?php
                query_posts('posts_per_page=1');
                if (have_posts()) {
                    while (have_posts()) : the_post();
                    if ( is_sticky() ) : ?>
    <div class="small-12 medium-6 large-4 columns">
        <div class="img-holder">
            <?php 
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
    the_post_thumbnail('sticky-hp-thumbnails');
} 
?>
            <?php if( get_field('sticky_sub_heading') ): ?>
            <div class="tag">
                <p>
                    <?php the_field('sticky_sub_heading'); ?>
                </p>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <div class="small-12 medium-6 large-4 columns">
        <h3><a href"<?php the_permalink() ?>">
            <?php the_title(); ?>
            </a></h3>
        <?php if( get_field('sticky_date') ): ?>
        <p class="sticky-date">
            <?php the_field('sticky_date'); ?>
        </p>
        <?php endif; ?>
        <p>
            <?php the_field('sticky_summary'); ?>
        </p>
        <a href="<?php the_permalink() ?>" class="button">Read More</a> </div>
    <?php endif;
  endwhile;
}
wp_reset_query();
?>

上面的代码哪里出错了?

【问题讨论】:

    标签: php sticky wordpress


    【解决方案1】:

    使用 posts_per_page 而不是“showposts”

    query_posts( 'posts_per_page=1' );
    

    来源: https://codex.wordpress.org/Function_Reference/query_posts

    更新:添加 WP_QUERY 代码以获取最新的置顶帖:

    <?php
    
    $args = array(
        'posts_per_page' => 1,
        'post__in'  => get_option( 'sticky_posts' ),
        'ignore_sticky_posts' => 1
    );
    $the_query = new WP_Query( $args );
     if ( $the_query->have_posts() ) : 
     while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    
    <div class="post">
    
        <h3><?php echo get_the_title(); ?></h3></a>
            <p><?php echo get_the_excerpt(); ?></p>
    
    </div>              
    
    
    <?php 
            endwhile; 
            endif;  
             wp_reset_postdata();
              ?>
    

    【讨论】:

    • 这不起作用,我还编辑了上面的代码,我错过了最后几行
    • 走 WP_Query 路线怎么样?因为这样的情况更简单、更有效、甚至更快查询?如果您可以使用 Wp_Query 完成它,您会选择它吗?如果编码是问题,我可以提供帮助。
    • 是的,我对任何事情都持开放态度
    • 好的,我用 WP_QUERY 版本更新我的答案以获取类似的数据。然后,您可以根据您的代码使用 AFC 字段等进行调整。
    • 我发布了上面的代码,我在本地主机上测试了该代码,该主机获取了最新的粘性帖子。并显示其标题和摘录。您可以根据需要显示的所有其他数据对其进行调整。
    【解决方案2】:

    解决您的问题的最简单解决方案(变通方法)是删除 while 循环。这样,您将只打印一个。

    当然,这是次优的,因为其他页面可能会被获取和使用;您可以尝试使用posts_per_page=1post_limits=1 看看是否能解决问题。

    【讨论】:

    • 我宁愿不使用“解决方法”方法,但它是一个很好的备份选项。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多