WordPress комментарии в неправильном порядке и Gravatar не работает - PullRequest
0 голосов
/ 10 октября 2018

Я новичок в WordPress и пытаюсь применить некоторые из моих знаний ООП, что привело меня к застреванию и поиску вашей помощи

Я создал класс комментариев:

    <?php

class Comments {
  public $commentSection;

  public function getComments() {
    //Get only the approved comments 
    $args = array(
      'status' => 'approve'
    );

    $comments_query = new WP_Comment_Query;
    $comments = $comments_query->query( $args );
    if ( $comments ) {
      $this->commentSection = "
      <article class='post'>
        <header>
          <h3> Comments</h3>
        </header>
        <p>
      ";
      foreach ( $comments as $comment ) {
        $this->commentSection .= 'Author: ' . wp_list_comments( array( 'avatar_size' => '16' ) );
        $this->commentSection .= 'Date: ' . comment_date();
        $this->commentSection .= 'Comment: ' . $comment->comment_content;
      }
    $this->commentSection .= "
        </p>
      </article>
    ";
    } else {
      $this->commentSection = '';
    }
    echo $this->commentSection;
  }
}

$commentsObj = new Comments();
$commentsObj->getComments();

Ниже приведена часть моей страницы index.php:

<section>
<div class="container">
  <?php
    if(have_posts()){
      while(have_posts()){
        the_post();
      ?>
        <article class="post">
          <header>
            <a href=" <?php the_permalink(); ?> " target='_self'><h1> <?php the_title(); ?> </h1></a>
          </header>
          <p> 
            <?php the_content(); ?> 
          </p>
        </article>
        <?php
          require_once('includes/comments.inc.php');
        ?>
      <?php
      }
    }
  ?>
</div>

Первая проблема: в результате комментарии к первому сообщению появляются в последнем сообщении.

Второй выпуск: знак граватара появляется рядом с текстом «Автор:» *

Пока у меня есть только один комментарий, связанный с первым постом, сделанным «Комментатором WordPress»

Если я использую comment_author (), тогда отображается «Anonymous» - разве у этого пользователя все еще должен быть отображен анонимный тип граватара?

Если я пытаюсь использовать get_avatar () вместоwp_list_comments (array ('avatar_size' => '16'), затем я получаю следующую ошибку:

Missing argument 1 for get_avatar(),

Как получить идентификатор автора для передачи в get_avatar?

Спасибо взаранее

1 Ответ

0 голосов
/ 10 октября 2018

Разобрался.Сначала вы должны загрузить объект, а затем вызвать функцию getComment из цикла while.Я выберу это как полный ответ через пару дней, когда система stackoverflow разрешит это

Вот класс комментариев:

    <?php

class Comments {
  public $commentSection;
  public $commentPostId;
  public $commentArr;

  public function getComments() {
    //Get only the approved comments 
    $args = array(
      'status' => 'approve'
    );

    $comments_query = new WP_Comment_Query;
    $comments = $comments_query->query( $args );
    if ( $comments ) {
      foreach ( $comments as $comment ) {
        $this->commentArr = get_comment( get_the_author_meta('ID') );
        $this->commentPostId = $this->commentArr->comment_post_ID;
        // echo " comment post id: " . $this->commentPostId;
        // echo " post id: " . get_the_ID();
        if($this->commentPostId == get_the_ID()){
          $this->commentSection = "
          <article class='post'>
            <header>
              <h3> Comments</h3>
            </header>
            <p>
          ";
          $this->commentSection .= 'Author: ' . get_avatar(get_comment_author_email(), $size = '16') . " comment id: " . $this->commentPostId;
          $this->commentSection .= 'Date: ' . comment_date();
          $this->commentSection .= 'Comment: ' . $comment->comment_content;
          $this->commentSection .= "
            </p>
          </article>
          ";
        }
      }
    echo $this->commentSection;
    } else {
      $this->commentSection = '';
    }
  }
}

$commentsObj = new Comments();

Ниже приведена часть страницы индекса:

      <?php
    require_once('includes/comments.inc.php');
  ?>
  <?php
    if(have_posts()){
      while(have_posts()){
        the_post();
      ?>
        <article class="post">
          <header>
            <a href=" <?php the_permalink(); ?> " target='_self'><h1> <?php the_title(); ?> </h1></a>
          </header>
          <p> 
            <?php the_content(); ?> 
          </p>
        </article>
        <?php
         // had to add this for home page
         if( get_comment( get_the_author_meta('ID') )->comment_post_ID == get_the_ID() ) {
            $commentsObj->getComments();
           }
        ?>
      <?php
      }
    }
  ?>
</div>

...