【问题标题】:Get link to (first) comment if there are comments today in Wordpress如果今天在 Wordpress 中有评论,则获取指向(第一个)评论的链接
【发布时间】:2023-03-16 01:42:01
【问题描述】:

我有这个功能和一个帖子的链接:

<?php
foreach ($results as $id) {
  $post = &get_post( $id->ID );
  setup_postdata($post);

  <li><a <?php href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a>

</li>
  <?php
} ?>

我想做的是:如果今天发布了评论,则显示指向已发布的第一条评论的链接。例如:如果今天有 4 个 cmets,我想要第一个评论的链接,而不是像现在这样的永久链接。

我尝试使用这个:
&lt;a &lt;?php href="&lt;?php the_permalink(get_comments-&gt;$post_id) ?&gt;"&gt;postname&lt;/a&gt; 和类似 comment_post_ID 的变体,但我无法让它工作。我做错了什么,我该怎么办?

【问题讨论】:

    标签: php wordpress function foreach comments


    【解决方案1】:

    我认为您可能对对象和函数感到困惑(或者您复制/粘贴错误)。当您尝试执行 get_cmets->$post_id 时,这是行不通的,因为 get_cmets 不是对象,get_comments is a function that accepts parameters。看看我在下面做了什么,因为它可能会对你有所帮助:

    <?php
    foreach ($results as $id) {
      $post = &get_post( $id->ID );
      setup_postdata($post);
    
      $args = array('post_id' => $id->ID, 'number' => 1);
      $lastComment = get_comments($args);
    
      if (!empty($lastComment[0]) and $lastComment[0]->comment_date > date('Y-m-d 00:00:00')){
        echo '<li><a href="'.get_comment_link($lastComment[0]).'">'.the_title().'</a></li>';
      }
    ?>
    

    get_cmets() 将进行一系列争论,在上面我传递了 postID 和 1 的计数,因此它只提取最后一条评论。它仍然会拉取今天未创建的 cmets,因此我添加的 if 条件应该仅在今天午夜之后发布评论时才回显它。

    【讨论】:

    • 再看一遍,我做了修改。我不知道它会 100% 起作用,这意味着更多的是让你走上正确的轨道。对于语法错误,您通常可以查找行号来尝试修复这些错误。我认为是 标记破坏了它。
    • 如果我测试它,它会给我Cannot use string offset as an array in 。我也想知道解决方案可能是什么。好问题。
    • 我只是在本地运行它,有两个问题。 1) 我使用 'count' => 1 而不是 'number' => 1。'count' 会告诉它只返回 cmets 数量的计数。 codex.wordpress.org/Function_Reference/get_comments 2) 我一直期待当它是一个对象时会返回一个数组。
    • 但这只是给我most recent comment,而不是most recent comment per post。请问你能解决这个问题吗?其实就是这个问题……
    • 如果你查看 $args 数组,它确实有 post_id 参数。因此,只要 $id->ID 发生变化(并且是正确的帖子 ID),它就应该只提取每个帖子的最后一条评论。
    猜你喜欢
    • 2020-01-09
    • 2015-01-24
    • 2016-12-28
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2023-03-13
    • 2016-03-21
    相关资源
    最近更新 更多