Can somebody help me to create a drop-down menu or (radio buttons) in WordPress comment form, so that a new user could make a selection of their user roles (for example teachers + students) ?
- Output from dropdown list or radio button would appear somewhere in
the comments area. - The best of all would also be if WordPress which already automatically populate
email, login name would also display new extra field info (dropdown list OR
radio button) to logged in users who already has their user roles
assigned - I don’t want to use a plugin for that.
- I know that there a lot of tutorials about adding extra custom
fields to the comment form including this web where I have found 3
similar requests unfortunately marked as duplicates, on my opinion
they are not dups at all, because there’s no code or tutorial for
using known values as (select – dropdown- radio) button.
comment_form_field_comment
to add aselect
element with alabel
.comment_post
to save the value.comment_text
to show the value for a comment.Sample code:
Update
I have rewritten the code to use a real MVC pattern. Explanation below.
Plugin header
Controller
Abstract meta data base class
Extended class for built-in roles
Extended class for custom selection of allowed roles
Basic comment meta view
Use a select field as view
Show the current role as view
As you can see, we have seven classes now:
Comment_Meta_Controller
Here, the other classes are combined to do something useful.
Comment_Meta_Data_Model
Base class to handle the comment data. Cannot be used as is, must be extended.
Comment_Meta_Builtin_Roles
Extends
Comment_Meta_Data_Model
and uses all built-in roles. I have used this for my tests; you should probably use the next class. Change the Controller to do that.Comment_Meta_Custom_Roles
Extends
Comment_Meta_Data_Model
. An alternative forComment_Meta_Builtin_Roles
.As you can see, you have to change just one method (function) to return an array of custom roles.
Comment_Meta_View
Base class for output. Cannot be used as is, must be extended.
Comment_Meta_Role_Selector
Extends
Comment_Meta_View
. Creates theselect
element. It doesn’t know anything about the source of your data and gets its values right from the View.Comment_Meta_Role_Display
Extends
Comment_Meta_View
. Shows the current value for a comment.Usage
To show the
select
field either …Or remove the line …
… and use in your comment form this code:
To set custom values for the allowed roles, remove the line …
… and uncomment the following line. Then edit
Comment_Meta_Custom_Roles
.To change the meta key, just change the value
'_comment_role'
. Make sure, you don’t use a built-in key from WordPress.That’s all.