php - 如何根据变量的值对列表进行排序? (php)

标签 php mysql wordpress

对熟悉 wordpress 的人的第一个问题:资源/系统负载明智直接查询 mysql 并在那里排序结果更好吗?或者使用 wordpress 钩子(Hook) WP_query 获取所有帖子并根据评论变量对它们进行排序?

我有这段代码,它可以获取所有内容。我想根据 comments_number( '0', '1', '%' );(评论较多的在顶部)对列表进行排序,并将显示的总数限制为前 4 个。

到目前为止我的代码:

 <ul>
    <?php

    global $post;
    $all_events = tribe_get_events(
      array(
        'eventDisplay'=>'upcoming',
        'posts_per_page'=>-1
    )
    );

    foreach($all_events as $post) {
    setup_postdata($post);
    ?>

    <li>
          <a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>">
                    <?php
                      if ( has_post_thumbnail () ) {
                          echo get_the_post_thumbnail(array(100,100));
                      } else {
                          echo '<img width="100" height="100" alt="'
                               .get_the_title().'" title="'
                               .strip_tags(get_the_excerpt()).'" src="'
                               .get_bloginfo('template_url')
                               .'/thumbs/event-recent-thumb-na.png">';
                      }
                    ?>
          </a>

          <h3><a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>">
              <?php the_title(); ?></a></h3>
          <span><?php echo tribe_get_start_date( $p->ID, true, 'M j, D.' ) . " - "
                         . tribe_get_end_date( $p->ID, true, 'D.' ); ?></span>
          <p><?php echo strip_tags(get_the_excerpt()); ?></p>
          <span class="eventinterested"><?php comments_number( '0', '1', '%' ); ?>
          <?php _e('interested so far','holidayge'); ?></span>
    </li>

    <?php } //endforeach ?>

          <?php wp_reset_query(); ?>

 </ul>

有没有办法修改 foreach 和那里的订单列表?我不是 php 程序员,但这似乎合乎逻辑......我正在阅读 Sort似乎是正确的解决方案?

最佳答案

MySQL 的查询速度比 PHP 快得多,因此您应该尽量不要请求比您想要的更多的帖子。将所有帖子加载到 PHP 中并不能很好地扩展。

我猜 tribe_get_events() 使用 get_posts()。如果那是正确的,这应该可以解决问题:

$all_events = tribe_get_events(
    array(
        'eventDisplay'   => 'upcoming',
        'posts_per_page' => 4,
        'orderby'        => 'comment_count',
        'order'          => 'DESC'
    )
);

更多信息可以在 the documentation on get_posts() 中找到.

关于php - 如何根据变量的值对列表进行排序? (php),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12446175/

相关文章:

php - 如何将数据插入到一个表中,其中表名是一个 php 变量,它会根据按钮的点击而变化?

javascript - 重定向到 url,如果 Jwplayer 加载媒体时出错

php - mysqli查询错误,不知道哪里出了问题

wordpress - 重定向 Azure 中托管的 Ghost 站点中的 WordPress URL

css - Wordpress 菜单居中对齐且间距均匀

javascript - WordPress -functions.php 不会注册我的 JavaScript 文件

php - 搜索查询在 Laravel 中不起作用

php - MySQL Select where number IN列

mysql - 无法启动 mySQL "mysqld: Too many arguments (first extra is ' 启动')。”

mysql - 使用表中另一个字段的值更新一个字段,其中字段值本身就是键