最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

hooks - Can't get ID of post that relates to the comment

programmeradmin2浏览0评论

I added custom checkbox to the comment form. I am trying to write the post ID of this comment in the database. But without success. I'm trying with something like this:

add_action( 'comment_post', 'save_chbox_in_db' );

function save_chbox_in_db() {
     $post_id = ??? // Can't get id...
     insert_to_db ( $email, $post_id ); // custom function
}

I tested these options:

global $post;
$post_id = $post->ID();

global $wp_query;
$post_id = $wp_query->post->ID;

$post_id = get_queried_object_id();

$post_id = get_the_ID();

As a result, I get zero or nothing. Where is the problem? Something with "comment_post" action? Or do I make some stupid mistake?

I added custom checkbox to the comment form. I am trying to write the post ID of this comment in the database. But without success. I'm trying with something like this:

add_action( 'comment_post', 'save_chbox_in_db' );

function save_chbox_in_db() {
     $post_id = ??? // Can't get id...
     insert_to_db ( $email, $post_id ); // custom function
}

I tested these options:

global $post;
$post_id = $post->ID();

global $wp_query;
$post_id = $wp_query->post->ID;

$post_id = get_queried_object_id();

$post_id = get_the_ID();

As a result, I get zero or nothing. Where is the problem? Something with "comment_post" action? Or do I make some stupid mistake?

Share Improve this question edited Jul 29, 2019 at 21:29 nmr 4,5672 gold badges17 silver badges25 bronze badges asked Jul 29, 2019 at 19:44 Mark71Mark71 33 bronze badges 1
  • Looking at the Codex the details for comment_post show $comment_ID is one of the properties passed to your function. codex.wordpress/Plugin_API/Action_Reference/comment_post – jdm2112 Commented Jul 29, 2019 at 21:01
Add a comment  | 

1 Answer 1

Reset to default 2

comment_post hook pass to attached functions 3 parameters. The fourth parameter of add_action() indicates to how many parameters the attached function will be able to access.

add_action( 'comment_post', 'save_chbox_in_db', 10, 3 );

function save_chbox_in_db( $comment_ID, $comment_approved, $commentdata )
{
     $post_id = (int)$commentdata['comment_post_ID'];
     //
     // other code
     //
}
发布评论

评论列表(0)

  1. 暂无评论