【问题标题】:Sorting posts alphabetically in WordPress在 WordPress 中按字母顺序对帖子进行排序
【发布时间】:2016-03-17 00:37:21
【问题描述】:

使用 WordPress Codex 中的 this information 我尝试在 WordPress 中按字母顺序对帖子进行排序,现在正在处理搜索结果。

这是模板中的默认代码,可用于搜索,但默认情况下会出现相反的时间顺序:

<?php while ( have_posts() ) : the_post(); ?>

    <?php get_template_part( 'content', apptheme_get_list_type() ); ?>

<?php endwhile; ?>

现在,我尝试将其更改为:

<?php

    while ( have_posts() ) : the_post();
        $args = array( 'posts_per_page' => -1, 'orderby'=> 'title', 'order' => 'ASC' );
        $sorted_posts = get_posts( $args );
    endwhile;

?>

<?php foreach ($sorted_posts as $post): setup_postdata($post); ?>

    <?php get_template_part( 'content', apptheme_get_list_type() ); ?>

<?php endforeach; ?>

这对排序顺序有效,但它会返回所有帖子,而不仅仅是适合搜索的帖子。我应该改变什么参数? (我对 PHP 很熟悉,但这是我第一次修改 WordPress 模板)

谢谢!

【问题讨论】:

  • 'posts_per_page' =&gt; -1 将所有帖子返回给您。只需在此处定义一个数字,您只会得到该数字。
  • 查询参数的完整列表可以在这里找到:codex.wordpress.org/Class_Reference/WP_Query
  • 该法典页面上写的大部分内容都是一堆废话。可悲的是,这不是抄本中唯一完全废话的页面。回到你的主/原始循环。您不应该运行自定义查询来代替主查询。回到 *all 页面上的主循环后,使用 pre_get_posts 更改主查询以满足您的需求

标签: php wordpress sorting


【解决方案1】:

我没试过,但应该可以:

add_filter('posts_orderby','custom_search_sort_custom',10,2);
function custom_search_sort_custom( $orderby, $query ){
    global $wpdb;

    if(is_search()) 
        $orderby =  $wpdb->prefix."posts.post_type ASC, {$wpdb->prefix}posts.post_title ASC";

    return  $orderby;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-02
    • 2020-04-05
    • 1970-01-01
    • 2011-06-17
    • 2012-02-18
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多