【问题标题】:Wordpress latest Posts AND comments feed?Wordpress 最新的帖子和评论提要?
【发布时间】:2010-07-06 20:24:39
【问题描述】:

我正在尝试编写一个自定义 SQL 查询,该查询将创建最新帖子和 cmets 的列表,但我无法想象如何做到这一点。

我可以按日期 DESC 拉出最新的 cmets,我可以按日期 DESC 拉出最新的帖子,但是我如何制作提要/查询以同时显示它们?

这是我的评论 SQL

SELECT comment_id, comment_content, comment_date
FROM wp_comments
WHERE comment_author = 'admin'
ORDER BY comment_date DESC

编辑:更清楚:

对不起,我应该更清楚一点。我想根据他们发生的日期有一个这样的列表:

Wordpress post 
wordpress post
wordpress comment
wordpress post
wordpress comment

因此,如果有人在 4 个月大的帖子上发表评论,它仍会显示在此“提要”的顶部

【问题讨论】:

    标签: sql mysql wordpress


    【解决方案1】:

    要仅根据两个表的最新时间戳获取列表,您需要使用 UNION:

    SELECT wc.comment_date AS dt
      FROM WP_COMMENTS wc
    UNION ALL
    SELECT wp.post_date AS dt
      FROM WP_POSTS wp
    ORDER BY dt
    

    ...其中dt 是保存任一表中记录的日期值的列的列别名。

    使用UNION ALL - 因为数据来自两个不同的表,所以不会更改要过滤掉的重复项。但这意味着您必须根据数据和数据类型从任一表中获取所需的其他列...

    【讨论】:

      【解决方案2】:

      我认为您最好的选择(并避免使用自定义 SQL)是获取最新的 X 个帖子和 X 个 cmets,循环遍历每个帖子并构建一个数组以将两者合并为一个“最新”数据集;

      $comments = get_comments('number=X');
      $posts    = get_posts('posts_per_page=X');
      
      $most_recent = array();
      
      foreach ($comments as $comment)
          $most_recent[strtotime($comment->comment_date_gmt)] = $comment;
      
      foreach ($posts as $post)
          $most_recent[strtotime($post->post_date_gmt)] = $post;
      
      unset($comments, $posts);
      
      krsort($most_recent);
      $most_recent = array_slice($most_recent, 0, X);
      
      foreach ($most_recent as $post_or_comment) {
      
          $is_post = isset($post_or_comment->post_date_gmt);
      
          // output comments and posts
      }
      

      它不是太漂亮,但它应该这样做。

      【讨论】:

      • 这似乎对我有用。有什么方法可以获取评论所针对的帖子的标题?
      • $comment_post_title = get_the_title($comment->comment_post_ID);
      【解决方案3】:

      不需要特殊的mySql,只需在循环中使用query_posts循环和get_comments函数即可。

       <?php query_posts('posts_per_page=10'); while (have_posts()) : the_post(); ?>
      
          <div>
              <a  href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title_attribute(); ?>"<?php the_title_attribute(); ?></a>
              <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php echo the_title(); ?></a>
              <?php 
                  $comments = get_comments();
                  foreach($comments as $comm) :
                    echo($comm->comment_author);
                    echo($comm->comment_content);
                  endforeach;
              ?>
          </div>
      
      <?php endwhile; ?>
      

      【讨论】:

      • 对不起,我应该更清楚一点。请参见上文。
      猜你喜欢
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 2012-07-07
      • 2021-05-14
      • 2011-05-20
      • 2011-10-31
      相关资源
      最近更新 更多