Wordpress Plugin Tutorial Part VII - Adding a Filter

We have used two action hooks up to now. They are 'save_post' and 'add_meta_boxes'. Today we will see how to add filter hooks. When data is processed in Wordpress they go through various filters. You can take a look at a list of filters on this page on Wordpress filters. Once we hook some code to a filter we get to filter those data as well.
The filter that we are interested in is 'comment_form_defaults'. The default values for the Wordpress comment form will go through this filter. So by hooking onto this filter we can change the 'Leave a Reply' message to what we want.

Change the constructor to look like the following to hook into the 'comment_form_defaults' filter.

public function __construct()
    add_action( 'add_meta_boxes',
                array( &$this, 'add_ccm_meta_box' ) );

                array(&$this,'ccm_save_data') ) ;
    //filter using the edit_cm function
               array(&$this, 'edit_cm') ) ;
Define the "edit_cm" function as follows inside our CustomCommentMessage class.
public function edit_cm($defaults){
    global $wp_query;
    $post_id = $wp_query->post->ID;
    $defaults["title_reply"] = get_post_meta($post_id,
    return $defaults;
As you can see the default values for the comment form get passed to the edit_cm function. In this function, we change the default value of the 'title_reply' array element to the custom value that we specified for the post.
The following images show the work of the plugin.

No comments:

Post a Comment