【问题标题】:Show only one sticky post at the top of a list of posts在帖子列表顶部仅显示一个置顶帖子
【发布时间】:2009-08-13 16:29:20
【问题描述】:

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

仅使用一个 query_posts() 即可获得奖励积分。

(我知道如何使用两个query_posts(),但我正在寻找一个不太费力的解决方案。)

【问题讨论】:

  • 问题是一旦我检查了另一个帖子的“置顶”选项,我的列表顶部会有两个置顶帖子,随着我继续添加新的“置顶”,这些帖子将继续增长“帖子。我只想显示 1 个置顶帖子。

标签: php wordpress wordpress-theming


【解决方案1】:

你试过插件吗?比如这个? http://wordpress.org/extend/plugins/wp-sticky/ 我可能更容易使用/修改它们。

【讨论】:

  • 谢谢,Umut,但我不想使用重复 WP Core 中已有功能的插件。
【解决方案2】:

您需要稍微调整一下这段代码,但它应该能让您朝着正确的方向前进。这是在修改用于拉取帖子的 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' );

【讨论】:

  • 感谢您的回复!哇,我没想到看起来如此简单的事情会涉及如此可怕的代码量——哎呀!这也让我想知道为什么 WP 核心团队不只是在 wp_posts 表中添加一个“粘性”列......
  • 如果您知道将返回正确结果的 sql 查询,您可以跳过前三个操作/函数,只在 requestSticky() 中返回查询。尽管在我的脑海中,我只能想象一个使用 UNION 查询来解决多重粘性问题的方法,这并没有真正节省任何 sql 开销,尽管它对 PHP 的工作量会更少。
猜你喜欢
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多