触发add_action一次

时间:2015-11-15 20:43:14

标签: php wordpress wordpress-plugin

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

<?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执行时,它会触发动作挂钩然后....

如何解决我的问题!任何想法?

1 个答案:

答案 0 :(得分:1)

did_action()是你的朋友。请在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();
?>