返回介绍

wp_new_comment()

发布于 2017-09-11 12:31:23 字数 11268 浏览 973 评论 0 收藏 0

wp_new_comment( array $commentdata,  bool $avoid_die = false )

Adds a new comment to the database.


description

Filters new comment to ensure that the fields are sanitized and valid before inserting comment into database. Calls ‘comment_post’ action with comment ID and whether comment is approved by WordPress. Also has ‘preprocess_comment’ filter for processing the comment data before the function handles it.

We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure that it is properly set, such as in wp-config.php, for your environment.

See https://core.trac.wordpress.org/ticket/9235


参数

$commentdata

(array) (Required) Comment data.

  • 'comment_author'
    (string) The name of the comment author.
  • 'comment_author_email'
    (string) The comment author email address.
  • 'comment_author_url'
    (string) The comment author URL.
  • 'comment_content'
    (string) The content of the comment.
  • 'comment_date'
    (string) The date the comment was submitted. Default is the current time.
  • 'comment_date_gmt'
    (string) The date the comment was submitted in the GMT timezone. Default is $comment_date in the GMT timezone.
  • 'comment_parent'
    (int) The ID of this comment's parent, if any. Default 0.
  • 'comment_post_ID'
    (int) The ID of the post that relates to the comment.
  • 'user_id'
    (int) The ID of the user who submitted the comment. Default 0.
  • 'user_ID'
    (int) Kept for backward-compatibility. Use $user_id instead.
  • 'comment_agent'
    (string) Comment author user agent. Default is the value of 'HTTP_USER_AGENT' in the $_SERVER superglobal sent in the original request.
  • 'comment_author_IP'
    (string) Comment author IP address in IPv4 format. Default is the value of 'REMOTE_ADDR' in the $_SERVER superglobal sent in the original request.

$avoid_die

(bool) (Optional) Should errors be returned as WP_Error objects instead of executing wp_die()?

Default value: false


返回值

(int|false|WP_Error) The ID of the comment on success, false or WP_Error on failure.


源代码

File: wp-includes/comment.php

function wp_new_comment( $commentdata, $avoid_die = false ) {
	global $wpdb;

	if ( isset( $commentdata['user_ID'] ) ) {
		$commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
	}

	$prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;

	/**
	 * Filters a comment's data before it is sanitized and inserted into the database.
	 *
	 * @since 1.5.0
	 *
	 * @param array $commentdata Comment data.
	 */
	$commentdata = apply_filters( 'preprocess_comment', $commentdata );

	$commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
	if ( isset( $commentdata['user_ID'] ) && $prefiltered_user_id !== (int) $commentdata['user_ID'] ) {
		$commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
	} elseif ( isset( $commentdata['user_id'] ) ) {
		$commentdata['user_id'] = (int) $commentdata['user_id'];
	}

	$commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
	$parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
	$commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;

	if ( ! isset( $commentdata['comment_author_IP'] ) ) {
		$commentdata['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
	}
	$commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '', $commentdata['comment_author_IP'] );

	if ( ! isset( $commentdata['comment_agent'] ) ) {
		$commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT']: '';
	}
	$commentdata['comment_agent'] = substr( $commentdata['comment_agent'], 0, 254 );

	if ( empty( $commentdata['comment_date'] ) ) {
		$commentdata['comment_date'] = current_time('mysql');
	}

	if ( empty( $commentdata['comment_date_gmt'] ) ) {
		$commentdata['comment_date_gmt'] = current_time( 'mysql', 1 );
	}

	$commentdata = wp_filter_comment($commentdata);

	$commentdata['comment_approved'] = wp_allow_comment( $commentdata, $avoid_die );
	if ( is_wp_error( $commentdata['comment_approved'] ) ) {
		return $commentdata['comment_approved'];
	}

	$comment_ID = wp_insert_comment($commentdata);
	if ( ! $comment_ID ) {
		$fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );

		foreach ( $fields as $field ) {
			if ( isset( $commentdata[ $field ] ) ) {
				$commentdata[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $commentdata[ $field ] );
			}
		}

		$commentdata = wp_filter_comment( $commentdata );

		$commentdata['comment_approved'] = wp_allow_comment( $commentdata, $avoid_die );
		if ( is_wp_error( $commentdata['comment_approved'] ) ) {
			return $commentdata['comment_approved'];
		}

		$comment_ID = wp_insert_comment( $commentdata );
		if ( ! $comment_ID ) {
			return false;
		}
	}

	/**
	 * Fires immediately after a comment is inserted into the database.
	 *
	 * @since 1.2.0
	 * @since 4.5.0 The `$commentdata` parameter was added.
	 *
	 * @param int        $comment_ID       The comment ID.
	 * @param int|string $comment_approved 1 if the comment is approved, 0 if not, 'spam' if spam.
	 * @param array      $commentdata      Comment data.
	 */
	do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'], $commentdata );

	return $comment_ID;
}

更新日志

Versiondescription
4.7.0The $avoid_die parameter was added, allowing the function to return a WP_Error object instead of dying.
4.3.0'comment_agent' and 'comment_author_IP' can be set via $commentdata.
1.5.0Introduced.

相关函数

Uses

  • wp-includes/wp-db.php: wpdb::strip_invalid_text_for_column()
  • wp-includes/functions.php: absint()
  • wp-includes/functions.php: current_time()
  • wp-includes/plugin.php: apply_filters()
  • wp-includes/plugin.php: do_action()
  • wp-includes/comment.php: preprocess_comment
  • wp-includes/comment.php: comment_post
  • wp-includes/comment.php: wp_get_comment_status()
  • wp-includes/comment.php: wp_filter_comment()
  • wp-includes/comment.php: wp_insert_comment()
  • wp-includes/comment.php: wp_allow_comment()
  • wp-includes/load.php: is_wp_error()
  • Show 7 more uses Hide more uses

Used By

  • wp-includes/comment.php: wp_handle_comment_submission()
  • wp-admin/includes/ajax-actions.php: wp_ajax_replyto_comment()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::pingback_ping()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::wp_newComment()

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 0You must log in to vote on the helpfulness of this note Contributed by Codex

    Basic Example

    
    global $post, $current_user; //for this example only :)
    
    $commentdata = array(
    	'comment_post_ID'      => $post->ID,             // To which post the comment will show up.
    	'comment_author'       => 'Another Someone',     // Fixed value - can be dynamic.
    	'comment_author_email' => 'someone@example.com', // Fixed value - can be dynamic.
    	'comment_author_url'   => 'http://example.com',  // Fixed value - can be dynamic.
    	'comment_content'      => 'Comment messsage...', // Fixed value - can be dynamic.
    	'comment_type'         => '',                    // Empty for regular comments, 'pingback' for pingbacks, 'trackback' for trackbacks.
    	'comment_parent'       => 0,                     // 0 if it's not a reply to another comment; if it's a reply, mention the parent comment ID here.
    	'user_id'              => $current_user->ID,     // Passing current user ID or any predefined as per the demand.
    );
    
    // Insert new comment and get the comment ID.
    $comment_id = wp_new_comment( $commentdata );
    
  2. Warning: If you set comment_type to one of these words:

    “all”, “comment”, “comments”, “pings”

    WordPress will save the comment with that type but you will be unable to retrieve it using normal WordPress comment functions. Here’s what happens to those reserved words inside `WP_Comment_Query`, where types are gathered into comment_type__in whether you send them via the type or type__in argument:

    • all – No 'comment_type__in' clause will be in query
    • comment or comments'' added to comment_type_in
    • pings'pingback','trackback' added to comment_type_in

    Because of this, you will not be able to retrieve the comment using “normal” WordPress functions. To get it, you will have to filter comments_clauses to ensure your type is added to the WHERE clause. For example, the following will replace the '' inserted instead of “comment” with 'comment':

    
    add_filter( 'comments_clauses', 'add_comment_to_clauses', 10, 2 );
    
    function add_comment_to_clauses( $clauses, $WP_Comment_object ) {
        
        // use regex to find the empty string in where clause
        $clauses['where'] = preg_replace_callback(
            "~(comment_type[ ]*IN[ ]*\\(.*)('')~i",
            function ( $matches ) {
                // $matches[1] was everything up to the '' 
                // $matches[2] was the empty string
                return $matches[1] . "'','comment'";
            },
            $clauses['where']
        );
    
        return $clauses;
    }
    

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文