gpt4 book ai didi

php - 触发 add_action 一次

转载 作者:搜寻专家 更新时间:2023-10-31 21:27:48 24 4
gpt4 key购买 nike

我希望当用户添加评论时,它会同时添加到另一个页面中。为此,我使用这段代码:

<?php
class PluginFonctionalities {

public function __construct() {
add_action( 'comment_post', array( $this, 'show_message_function' ), 10, 2 );
}

public function show_message_function( $comment_ID, $comment_approved ) {
if( 1 === $comment_approved ){

$comment= get_comment($comment_ID );
$the_post_id = 7;

$commentdata = array(
'comment_post_ID' => $the_post_id,
'comment_author' => $comment->comment_author,
'comment_author_email' => $comment->comment_author_email,
'comment_author_url' => $comment->comment_author_url,
'comment_content' => $comment->comment_content,
'comment_type' => $comment->comment_type,
'comment_parent' => 0,
'user_id' => $comment->user_id,
);
$comment_id_new = wp_new_comment( $commentdata );

}
}
}

$pf = new PluginFonctionalities();
?>

开心的事:分两页添加评论

不好的地方那是在第 7 页中多次添加评论(循环),因为当 wp_new_comment 执行时,它触发了 action hook 然后 ....

我该如何解决我的问题!?有什么想法吗?

最佳答案

did_action() 是你的 friend 。阅读 https://codex.wordpress.org/Function_Reference/did_action .

所以对于您的代码,我会这样做:

<?php
class PluginFonctionalities {

public function __construct() {
add_action( 'comment_post', array( $this, 'show_message_function' ), 10, 2 );
}

public function show_message_function( $comment_ID, $comment_approved ) {
if( did_action( 'comment_post' ) === 1 ){
if( 1 === $comment_approved ){

$comment= get_comment($comment_ID );
$the_post_id = 7;

$commentdata = array(
'comment_post_ID' => $the_post_id,
'comment_author' => $comment->comment_author,
'comment_author_email' => $comment->comment_author_email,
'comment_author_url' => $comment->comment_author_url,
'comment_content' => $comment->comment_content,
'comment_type' => $comment->comment_type,
'comment_parent' => 0,
'user_id' => $comment->user_id,
);
$comment_id_new = wp_new_comment( $commentdata );
}
}
}
}

$pf = new PluginFonctionalities();
?>

关于php - 触发 add_action 一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com