2009-08-13 55 views
0

在我的主页上有一个帖子列表,在顶部我只想显示最近的“粘贴”帖子,其次是其他帖子。有没有办法做到这一点?在帖子列表顶部只显示一个粘贴帖

只使用一个query_posts()的奖励积分。

(我知道如何使用两个query_posts()做到这一点,但我正在寻找一个减轻了负担的解决方案。)

+0

问题是,当我检查另一篇文章的“粘性”选项时,我将在列表顶部有两个粘性文章,随着我继续添加新的“粘性”文章,这些文章将继续增长。我只想要显示一个粘贴文章。 – gabriel 2009-08-14 03:16:05

回答

0

你需要调整这个码了一点,但它应该让你在正确的去方向。这是做什么修改用于拉帖子的SQL查询。

在你的query_posts()之前;添加以下代码:

function selectSticky($sql){ 
    global $sticky_posts, $wpdb; 

    $sticky_posts = get_option('sticky_posts'); 
    $sticky_posts = implode(', ', $sticky_posts); 

    return "IF({$wpdb->posts}.ID IN ($sticky_posts), 2, 1) as sticky, ".$sql; 
} 

function whereSticky($sql){ 
    global $sticky_posts, $wpdb; 

    $sql .= " OR {$wpdb->posts}.ID IN ($sticky_posts)"; 
    return $sql; 
} 

function orderSticky($sql){ 
    $sql = "sticky DESC, ".$sql; 
    return $sql; 
} 

// just for checking sql, you can remove this once everything works 
function requestSticky($sql){ 
    echo $sql."<br/><br/>"; 
    return $sql; 
} 

add_action('posts_fields', 'selectSticky'); 
add_action('posts_where', 'whereSticky'); 
add_action('posts_orderby', 'orderSticky'); 
add_action('posts_request', 'requestSticky'); 
+0

感谢您的回应!哇,我没有想到这样简单的事情会涉及这么多可怕的代码!这也让我想知道为什么WP核心团队不只是在'wp_posts'表中添加一个“粘性”列... – gabriel 2009-08-14 03:04:00

+0

如果您知道将返回正确结果的sql查询,则可以跳过前三个操作/函数,只需在requestSticky()中返回查询即可。尽管不是我的头顶,但我只能想象使用UNION查询解决多重粘性问题的方法,它不会真正节省任何SQL开销,但对于PHP而言,这不会有太大的工作量。 – postpostmodern 2009-08-14 16:50:49