I’m writing a WordPress plugin with a widget. In my jQuery code i’d like to point to that widget, so I though giving it an HTML ID would be nice. (Edited, thanks for pointing out.)
After doing some searching on the internet (and the Codex) I know that I can give ID’s to the widgets in the theme, but it’s not what I was looking for. This method has flaws. Changing the theme may cause errors (of course, I know it has to be changed in the functions.php, but it’s just meh). The other thing is that my widget got a number which may change without me knowing.
So to be 100% sure it works and will work in the future, can I give my widget my own ID?
I might not understand your question exactly and what
"ID"
do you mean ( widget ID , or actual HTML div ID – which are actually one and the same.. ) but If you have read the codex , the example for how to give an ID is given there ..Another way to do the same ( and helpul if you are talking about
HTML
elements likedivs
– you can assign aclass
)Note that a numerator will be automatically added to your widget´s ID based on how many instances were initiated like :
etc …
EDIT I – after comments
At any rate , IMHO it is a bad idea to hard-code a fixed
ID
in a widget for the simple reason that the preference for a widget from the developer point of view is to always allow support for multiple instances . Giving an anHTML ID
anywhere on the widget will cause validation errors AND in the case ofjQuery
– alsoJS
errors for the simple cause that if a user will have 2 widgets , it will also have a duplicated ID .In other words – It is the exact opposite of your statement in the original question.
Giving a fixed hard coded ID to your widget will in fact ensure that it will NOT work 100% of the time.
The preference is always to target such issues with a
class
( or with something likediv[id^="my_widget_id"]
) and let wordpress “do it´s thing” ( by auto incrementing IDs ).For the exact same reason – a theme should always have the same structure in the
register sidebar()
function like so :This will permit the specific sidebar to
auto increment
the ID of the widgets in order to avoid the above mentioned problem .From the codex :
All that being said, and if you are insisting of giving a hard-coded fixed ID somewhere there ( instead of a the methods described above ) you can always put that at a nested
div
orspan
INSIDE your widget´s HTML output, But I would think that if you have read attentively this answer – you will avoid it now.Now,- since you have not included any code in your question ( which is always a bad practice here on SE ) there is little more I can do to help. If you encounter any problems targeting the widget without an ID – I suggest you to open a new question and maybe point a link at the comments here, so myself ( and others ) can help you with it ..