【问题标题】:Wordpress query for sticky posts that are scheduledWordpress 查询预定的粘性帖子
【发布时间】:2014-05-20 19:31:54
【问题描述】:

我正在使用以下查询在 Wordpress 中显示 4 个最新的置顶帖子。

<?php
$sticky = get_option( 'sticky_posts' ); // Get all sticky posts
rsort( $sticky ); // Sort the stickies, latest first
$sticky = array_slice( $sticky, 0, 4 ); // Number of stickies to show
query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) ); // The query

if (have_posts() ) { while ( have_posts() ) : the_post(); ?>

ALL OF MY OUTPUTTED CODE GOES HERE - EDITED OUT TO SAVE SPACE

<?php endwhile;?>
<?php } else { echo ""; }?>
<?php wp_reset_query(); ?>

这很好用,但是如果我有一个预定的置顶帖(在未来的某个日期出现),查询会忽略它作为置顶帖之一,只显示 3 - 而不是它应该显示的 4?

如何修改以下代码以确保不显示预定的置顶帖,并且我仍然保留 4 个置顶帖?

下面的更新代码显示所有帖子 - 不仅仅是最近的 4 个粘性帖子。

<?php
$sticky = get_option( 'sticky_posts' );
$args = array(
'posts_per_page' => 4,
'post__in'  => $sticky,
'paged' => 1,
'ignore_sticky_posts' => 1
);     

if (have_posts() ) { while ( have_posts() ) : the_post(); ?>

ALL OF MY OUTPUTTED CODE GOES HERE - EDITED OUT TO SAVE SPACE

<?php endwhile;?>
<?php } else { echo ""; }?>
<?php wp_reset_query(); ?>

【问题讨论】:

    标签: php wordpress loops sticky


    【解决方案1】:

    限制您在查询中返回的帖子数量,而不是通过对数组进行切片。

    来自http://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters

    $sticky = get_option( 'sticky_posts' );
    $args = array(
        'posts_per_page' => 4,
        'post__in'  => $sticky,
        'ignore_sticky_posts' => 1
    );
    

    请查看上面的 Codex 参考以获取循环示例。这是您需要的要点。

    // The Query
    $the_query = new WP_Query( $args );
    
    // The Loop
    if ( $the_query->have_posts() ) {
        echo '<ul>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            echo '<li>' . get_the_title() . '</li>';
        }
        echo '</ul>'; 
    } else {
        // no posts found
    }
    
    /* Restore original Post Data */
    wp_reset_postdata();
    

    注意新的 WP_Query 如何接受上面的参数。在您发布的代码中,您没有对它们做任何事情。

    【讨论】:

    • 现在列出了所有的置顶帖子。如何将其限制为仅最近的 4 个?
    • posts_per_page 参数应将其限制为最近的 4 个,您是否正在做其他可以改变这一点的事情?
    • 按原样使用您的代码。它作为数组切片设置为 4,但 posts_per_page 无效。有任何想法吗?再次感谢您的尝试。
    • 尝试在查询中添加'paged' =&gt; 1
    • 仍然没有效果。当我进入博客设置并更改“博客页面最多显示”数量时,会产生影响。这似乎弄乱了您的代码及其将 posts_per_page 设置为 4 的尝试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多