Create a Minecraft Item that Executes a Command [duplicate]

I am using creative mode to tag Minecraft villagers as an adult or child.

Here is the code I am using: /data merge entity @e[type=villager,limit=1,sort=nearest] {Tags:["child"]} /data merge entity @e[type=villager,limit=1,sort=nearest] {Tags:["adult"]}

However, I want players in survival mode to be able to add these data tags to villagers. Can I create an item that, when right clicked, will execute one of these commands? I think I may need to use a carrot on a stick (since it can detect a right click) but I am not certain. Ideally, I would like to use two sticks: one called "child age wand" and the other called "adult age wand." How would I do this?


The only item which supports right-click detection without using tricky methods is the carrot on a stick so that's what I will use for this example.

First, you need an objective to track when the player right-clicks with it. This only needs to be initialized once so you can run it in chat.

/scoreboard objectives add clicked minecraft.used:minecraft.carrot_on_a_stick

this command needs to run in a repeating command block:

/execute at @a[scores={clicked=1..},nbt={SelectedItem:{id:"minecraft:carrot_on_a_stick",tag:{display:{Name:"\"name_here\""}}}}] run tag @e[type=villager,limit=1,sort=nearest] add child

^ write one more for the other carrot on a stick but change the name and tag. This command should be running in a chain (always active) command block attached to the repeating one:

/scoreboard players reset @a[scores={clicked=1..}] clicked

to generate your carrots on a stick, use this command:

/give @s minecraft:carrot_on_a_stick{display:{Name:"\"name_here\""}}