WordPressのコメントに項目を追加する方法
WordPressに掲示板の機能をコメント機能で対応しようとすると、項目が足りなっ!!
って事がありますよね〜
その時に項目を追加する方法をWordPantsの記事で発見したので、コメントタイトルを追加する方法を備忘的にまとめときます。
※WordPantsってネーミングが秀逸w
(1)コメントタイトル欄を追加
<? php <td align="left" bgcolor="#FEB3CA"><span class="style1">書き込みタイトル<br> <span class="style3">※最大30文字</span></span></td> <td align="left" bgcolor="#FFFFFF"> <input id="comment-title" name="comment-title" type="TEXT" size=56 maxlength="30"> </td> ?>
(2)コメントタイトルの登録、更新機能を実装する
comment_post、edit_commentをフックに使う
<? php function comment_field( $comment_id ) { if ( !$comment = get_comment( $comment_id ) ) return false; $custom_key_title = 'comment-title'; $get_comment_title = esc_attr( $_POST[$custom_key_title] ); if ( '' == get_comment_meta( $comment_id, $custom_key_title ) ) { add_comment_meta( $comment_id, $custom_key_title, $get_comment_title, true ); } else if ( $get_comment_title != get_comment_meta( $comment_id, $custom_key_title ) ) { update_comment_meta( $comment_id, $custom_key_title, $get_comment_title ); } else if ( '' == $get_comment_title ) { delete_comment_meta( $comment_id, $custom_key_title ); } return false; } add_action( 'comment_post', 'comment_field' ); add_action( 'edit_comment', 'comment_field' ); ?>
(3)管理画面でコメントタイトルの修正機能を実装する。
add_meta_boxes_commentをフックに使う
<? php add_action( 'add_meta_boxes_comment', 'comment_field_box' ); function comment_field_box() { global $comment; $comment_ID = $comment->comment_ID; $custom_key = 'post_reviews_date' ; $custom_key_title = 'comment-title' ; $noncename = $custom_key . '_noncename' ; $get_comment_title = esc_attr( get_comment_meta( $comment_ID, $custom_key_title, true ) ); echo '<input type="hidden" name="' . $noncename . '" id="' . $noncename . '" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />' . "\n"; echo '<p><b><label for="comment-title">【コメントタイトル】</label></b></p><p><input id="' . $custom_key_title . '" name="' . $custom_key_title . '" type="text" value="' . $get_comment_title . '" size="56" maxlength="30"/></p>' . "\n"; } ?>
(4)管理画面のコメント一覧にコメントタイトルを追加しちゃえ〜
manage_edit-comments_columns、manage_comments_custom_columnをフックに使う
<? php function manage_comment_columns($columns) { $columns['comment-title'] = "コメントタイトル"; return $columns; } function add_comment_columns($column_name, $comment_id) { if( $column_name == 'comment-title' ) { $comment_title = get_comment_meta( $comment_id, 'comment-title', true ); echo attribute_escape($comment_title); } } add_filter( 'manage_edit-comments_columns', 'manage_comment_columns' ); add_action( 'manage_comments_custom_column', 'add_comment_columns',null, 2); ?>