主页/WordPress笔记/博客文章/综合文章/如何在 WordPress 中允许用户订阅评论

如何在 WordPress 中允许用户订阅评论

Bug编译狮

Bug编译狮

在 WordPress 中允许用户订阅评论是一种常见的功能设置,它可以让评论者选择是否接受邮件通知来接收他们发表的评论。这种功能不仅提高了用户的参与度和互动性,还能帮助管理员更好地管理评论并及时回复重要问题。下面我将详细说明如何在 WordPress 中启用评论订阅,并提供一个简单的示例代码。

步骤 1: 登录到您的 WordPress 管理后台

首先,登录到您的 WordPress 网站的管理后台(通常是通过浏览器访问 http://yourdomain.com/wp-admin/)。

步骤 2: 进入“编辑”模式

点击右上角的“菜单”,然后选择“编辑”。

步骤 3: 找到“评论”选项

在左侧菜单栏中找到并点击“评论”。

步骤 4: 启用评论订阅

在评论设置页面,找到“订阅评论”的选项卡。在这里,您可以查看当前的订阅状态以及相关的配置选项。

  • 启用订阅:如果您希望所有新评论都自动订阅,请勾选“自动订阅新评论”。
  • 取消订阅:如果您希望用户可以选择是否订阅评论,则应取消勾选“自动订阅新评论”。
  • 更改默认设置:如果想要改变默认的订阅行为,可以在“自定义”部分进行调整。

示例代码:

假设您已经启用了“自动订阅新评论”,那么当有人发布新的评论时,系统会自动向他们的电子邮件地址发送一封确认邮件,询问他们是否同意接收评论更新通知。

// 定义变量
$commenter = wp_get_current_commenter();
$user_id = $commenter['user_id'];
$email = $commenter['email_address'];

// 发送订阅确认邮件
function send_subscribe_confirmation_email($subject, $message) {
    // 设置邮件参数
    $to = $email;
    $from = 'your-email@example.com';
    $headers = "From: " . $from . "rn";

    // 检查是否已订阅
    if (!get_option('autoapprove')) {
        $confirmation_link = add_query_arg(array(
            'action' => 'subscribe',
            'user_id' => $user_id,
        ), admin_url('/comments.php'));

        // 构建邮件正文
        $body = '<html>
                  <head>
                    <title>' . esc_html__( 'Subscribe Confirmation', 'text_domain' ) . '</title>
                  </head>
                  <body style="font-family: Arial; color: #333;">
                    <h1>' . esc_html__( 'Thank you for subscribing!', 'text_domain' ) . '</h1>
                    <p>' . esc_html__( 'You have successfully subscribed to our newsletter.', 'text_domain' ) . '</p>
                    <p><a href="' . esc_url( $confirmation_link ) . '">' . esc_html__( 'View your subscription details here', 'text_domain' ) . '</a></p>
                  </body>
                </html>';

        // 发送邮件
        wp_mail($to, $subject, $body, $headers);
    }
}

使用步骤及效果:

  1. 启用自动订阅:确保在评论设置中开启了“自动订阅新评论”。
  2. 发送确认邮件:当有新评论时,系统会检查是否有未被订阅的评论。如果有,就会发送一封确认邮件给评论者。
  3. 用户反馈:评论者收到确认邮件后,可以查看邮件中的链接以激活订阅。

这只是一个基本的示例,实际应用中可能需要根据具体需求进一步定制邮件模板和功能实现。

黑板前的Bug语法讲师

黑板前的Bug语法讲师

讲解目标:

本课程将教授您如何在WordPress网站上设置评论订阅功能,使您的站点更加互动和个性化。

教学大纲:

  1. 了解评论订阅
  2. 创建并配置评论表单
  3. 使用WordPress插件实现自动回复
  4. 设置评论格式

第一步:了解评论订阅

首先,我们需要理解评论订阅的概念。评论订阅是一种让用户选择是否收到新的评论通知的方式。这可以通过在WordPress主题或插件中设置来实现。

示例代码:

<?php
/**
 * Plugin Name: Comment Subscription
 * Description: Automatically subscribe users to comments.
 */

// Register the comment subscription form.
add_action( 'comment_form', 'my_comment_form' );

function my_comment_form() {
  ?>
  <div class="subscribe">
    <form action="" method="post" id="comment-subscribe-form">
      <label for="email">Subscribe by email:</label>
      <input type="email" name="email" id="email" />
      <button type="submit" class="subscribe-button">Subscribe</button>
    </form>
  </div>
  <?php
}

解释:

  • add_action( 'comment_form', 'my_comment_form' ); 这行代码定义了一个函数,当用户提交评论时,会调用这个函数。
  • my_comment_form() 函数中,我们设置了HTML结构,包括一个表单,用于输入用户的电子邮件地址。

第二步:创建并配置评论表单

接下来,我们将在WordPress中创建一个表单,以便用户可以订阅评论。此步骤需要一些基础的HTML知识。

示例代码:

<!-- 在主题文件夹下的wp-content/plugins目录下创建一个名为CommentSubscription.php的文件 -->
<?php
class CommentSubscription extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'comment_subscription',
            'Comment Subscription',
            array('description' => __( 'Automatically subscribe users to comments.' ))
        );
    }

    public function widget($args, $instance) {
        extract($args);
        echo $before_widget;
        if ( ! empty( $instance['email'] ) ) {
            printf( $before_title . esc_html( $instance['title'] ) . $after_title, esc_html( get_bloginfo( 'name' ) ), esc_html( $instance['email'] ) );
        }
        $output = '';
        $output .= '<p><strong>Email Subscriptions:</strong>';
        $output .= '<ul>';
        foreach ( $instance as $key => $value ) {
            $output .= "<li>" . $key . ": " . esc_attr( $value ) . "</li>";
        }
        $output .= '</ul></p>';
        echo $before_content;
        do_action( 'comment_subscribed', $instance['email'] );
        echo $after_content;
        echo $after_widget;
    }

    public function update( $new_instance, $old_instance ) {
        $instance = wp_parse_args( $new_instance, $old_instance );
        return $instance;
    }

    public function form( $instance ) {
        $defaults = array(
            'email' => ''
        );
        $instance = wp_parse_args( (array) $instance, $defaults );
        $options = get_option( 'comment_subscription_options' );
        if (!empty( $options[$instance['email']] )) {
            echo "<p>Sorry, this user has already been subscribed.</p>";
            exit();
        }
        $output = "";
        $output .= "<label for='email'>Email Address:</label>";
        $output .= "<input type='email' name='email' id='email' value='" . esc_attr( $instance['email'] ) . "' />";
        $output .= "<p><input type='checkbox' name='save_email' value='1' ".checked( true, $instance['email'], false )."> Save me on future posts</p>";
        echo $output;
    }

    public function widget_text() {
        echo $this->get_title();
    }

}

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
} 

register_widget( 'CommentSubscription' );

解释:

  • 创建一个新的类(如 CommentSubscription),继承自 WP_Widget
  • 设置一个描述文本。
  • 添加一个方法 widget 来处理用户提交的评论表单。
  • widget 方法中,输出标题、电子邮件地址等信息。
  • 提供更新实例的方法 update 和更新表单的示例 form 方法。
  • 定义一个方法 widget_text 来显示标题。

第三步:使用WordPress插件实现自动回复

为了简化评论流程,您可以考虑使用WordPress插件来提供自动回复功能。这些插件通常包含自动回复的模板,可以帮助减少工作量。

示例代码:

<plugin>
  <name>AutoReply</name>
  <author>Email Notifications</author>
  <author_url>https://example.com</author_url>
  <icon>fa fa-comment</icon>
  <version>1.0</version>
  <description>This plugin allows you to automatically reply to all comments with a custom message.</description>

  <requirements>
    <theme>WordPress Theme</theme>
  </requirements>

  <description>This plugin allows you to automatically reply to all comments with a custom message.</description>
  <script>
    function initPlugin() {
      const postType = wp.vocabs.getByName("comment");
      const autoReplyMessage = wp.vocabs.getByName("auto-reply-message");

      // Set up the plugin's settings and hooks here.

      // Initialize the auto-reply feature.
      wp.vocabs.register( "auto-reply-message", {
        name: "Auto Reply Message",
        singularName: "Auto Reply Message",
        path: "/auto-reply-message/",
        label: "Auto Reply Message",
        context: "all",
        count: 5,
        description: "This is an example of a custom message.",
        category: "Custom Messages",
        status: "publish"
      });

      // Add a new comment hook to handle auto-reply functionality.
      wp.add_filter( 'comments_post_link', 'add_auto_reply_to_comments_link', 9999, 2 );

      // Add a filter to allow for dynamic content in the reply area.
      wp.customize( 'reply_area', function( editor ) {
        editor.setEditorValue(`
          <h3>Example Auto-Reply</h3>
          <p>This is an example of how to use the auto-reply feature. You can customize the message using the following shortcode:</p>
          <pre>
            {{ auto-reply_message }}
          </pre>
        `);
      } );
    }

    function add_auto_reply_to_comments_link( $link ) {
      $link .= '/?auto-reply=on';
      return $link;
    }

    function auto_reply_on_page() {
      global $post;

      // Check if the post is a comment post.
      if ( is_comment_post() ) {
        // Get the current comment object.
        $comment = get_comment();

        // If there's no comment object, bail out early.
        if ( ! $comment ) {
          return;
        }

        // Get the current post ID.
        $current_post_id = $post->ID;

        // Check if the comment was submitted via the comment form.
        if ( isset($_POST['comment']) && $_POST['comment'] == $comment->comment_ID ) {
          // Get the auto-reply message from the custom messages table.
          $message = wp_vocabulary_get_by_name('auto-reply-message');

          // Format the message and replace placeholders.
          $formatted_message = str_replace('{post_title}', $post->post_title, $message->singularName);

          // Insert the formatted message into the reply area.
          $post_content = wpautop( strip_shortcodes( $comment->comment_content ) );
          $post_content = preg_replace('/{{ auto-reply-message }}/', $formatted_message, $post_content);
          $post_content = apply_filters('the_content', $post_content);

          // Update the comment content with the formatted message.
          update_comment_meta( $comment->comment_ID, 'comment_content', $post_content );
        }
      }
    }
  </script>
</plugin>

解释:

  • 使用 wp_vocabs 提供了自动回复消息的类别管理。
  • 添加自动回复到评论页面的功能。
  • 自动回复消息通过定制化的内容区域展示。

第四步:设置评论格式

最后,为用户提供一种方便的方式来查看和管理他们的评论。这通常涉及在WordPress主题或插件中添加特定的样式规则或功能。

示例代码:

/* 在主题文件夹下的wp-content/themes/your-theme/css目录下创建一个名为custom.css的文件 */
body.comment-list {
  font-family: Arial, sans-serif;
  font-size: 16px;
  color: #333;
  background-color: #fff;
  padding: 20px;
  margin: 0;
  -webkit-column-count: 3;
  column-count: 3;
}

.post {
  display: inline-block;
  width: calc((100% / 3) - 8px);
}

.comment {
  margin-bottom: 10px;
}

.reply {
  text-align: right;
  padding-right: 10px;
}

.author {
  margin-top: 5px;
}

.date {
  margin-top: 5px;
}

.reply a {
  color: #333;
  cursor: pointer;
}

.reply a:hover {
  text-decoration: underline;
}

.reply a span {
  cursor: pointer;
}

解释:

  • 样式规则应用于具有 comment-list 类的页面元素,以调整列表布局。
  • 根据评论类型(如作者、日期等)设置不同的样式属性。

总结

通过以上步骤,您已经成功地实现了评论订阅、自动回复以及评论格式的设置。这样,无论用户何时访问您的网站,都可以轻松接收新评论的通知,并享受个性化的用户体验。