使用筛选器更改备注字段(未成功)

时间:2022-01-13 作者:Marcus Wood

我是做错了还是应该这样做?无论我访问哪个帖子,它都会陷入一个无休止的循环。。

This is the code:

add_filter(\'comment_form_fields\', \'comment_form_args\');
function comment_form_args( $fields ) {

  if ( ! is_user_logged_in() ) {
    comment_form(array(
    \'label_submit\' => __(\'Submit for Approval\'),
    \'comment_notes_before\' => \'\',
    \'title_reply\' => \'Need to ask something? Go ahead.\',
    \'title_reply_to\' => \'Your reply to %s\',
    \'comment_field\' => \'<p class="comment-form-comment"><label for="comment">\' . _x( \'\', \'noun\' ) . \'</label><br /><textarea id="comment" name="comment" aria-required="true"></textarea></p>\',
    \'comment_notes_after\' => \'<p>Be polite and specific. Spam will be deleted.</p>\'
    )
  );
  } else {

    comment_form(array(
    \'label_submit\' => __(\'Submit\'),
    \'comment_notes_before\' => \'\',
    \'title_reply\' => \'\',
    \'title_reply_to\' => \'Answer %s\',
    \'comment_field\' => \'<p class="comment-form-comment"><label for="comment">\' . _x( \'\', \'noun\' ) . \'</label><br /><textarea id="comment" name="comment" aria-required="true"></textarea></p>\',
    \'comment_notes_after\' => \'\'
    )
  );

  }
}

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

您的代码有两个主要问题:

缺少一个return $fields; 或者返回值-Filter回调必须始终返回某些内容,这通常是过滤后的第一个参数(无论回调是否实际修改)。

不要打电话comment_form() 因为comment_form_fields 在该函数中激发,因此您将遇到一个永无止境的循环,就像您自己看到的一样。

查看调用comment_form(), 我想你应该用的钩子是comment_form_defaults 而不是comment_form_fields.

因此,请尝试以下方法:

// Use comment_form_defaults and not comment_form_fields.
add_filter( \'comment_form_defaults\', \'comment_form_args\' );

function comment_form_args( $args ) {
    if ( ! is_user_logged_in() ) {
        return array_merge( $args, array(
            \'label_submit\'         => __( \'Submit for Approval\' ),
            \'comment_notes_before\' => \'\',
            \'title_reply\'          => \'Need to ask something? Go ahead.\',
            \'title_reply_to\'       => \'Your reply to %s\',
            \'comment_field\'        => \'<p class="comment-form-comment"><label for="comment">\' . _x( \'\', \'noun\' ) . \'</label><br /><textarea id="comment" name="comment" aria-required="true"></textarea></p>\',
            \'comment_notes_after\'  => \'<p>Be polite and specific. Spam will be deleted.</p>\'
        ) );
    } else {
        return array_merge( $args, array(
            \'label_submit\'         => __( \'Submit\' ),
            \'comment_notes_before\' => \'\',
            \'title_reply\'          => \'\',
            \'title_reply_to\'       => \'Answer %s\',
            \'comment_field\'        => \'<p class="comment-form-comment"><label for="comment">\' . _x( \'\', \'noun\' ) . \'</label><br /><textarea id="comment" name="comment" aria-required="true"></textarea></p>\',
            \'comment_notes_after\'  => \'\'
        ) );
    }
}