How to Add Tags in WordPress: Simple Steps for Beginners
To add a
tag in WordPress, go to the post editor and find the Tags box on the right side, then type your tag and click Add. Alternatively, you can add tags programmatically using the wp_set_post_tags() function in your theme or plugin code.Syntax
There are two main ways to add tags in WordPress: through the admin dashboard or programmatically in code.
- Admin Dashboard: Use the
Tagsbox in the post editor. - Programmatically: Use the
wp_set_post_tags( $post_id, $tags, $append )function.
Parameters for wp_set_post_tags():
$post_id: The ID of the post to add tags to.$tags: A string or array of tag names.$append: Boolean to add tags without removing existing ones (true) or replace them (false).
php
wp_set_post_tags( int $post_id, string|array $tags, bool $append = false )
Example
This example shows how to add tags to a post with ID 123 using code. It adds the tags "WordPress", "Tutorial", and "Beginner" and keeps any existing tags.
php
<?php $post_id = 123; $tags = array('WordPress', 'Tutorial', 'Beginner'); wp_set_post_tags($post_id, $tags, true); ?>
Output
Tags "WordPress", "Tutorial", and "Beginner" are added to post ID 123 without removing existing tags.
Common Pitfalls
Common mistakes when adding tags in WordPress include:
- Trying to add tags without selecting the correct post ID in code.
- Forgetting to set
$appendtotruewhen you want to keep existing tags, which causes tags to be replaced. - Typing tags incorrectly or with extra spaces in the admin dashboard, which creates unwanted tags.
Always double-check tag spelling and post IDs.
php
<?php // Wrong: replaces all tags unintentionally wp_set_post_tags(123, array('NewTag'), false); // Right: adds new tag without removing existing ones wp_set_post_tags(123, array('NewTag'), true); ?>
Quick Reference
| Action | Method | Notes |
|---|---|---|
| Add tag via admin | Post editor > Tags box | Type tag name and click Add |
| Add tags programmatically | wp_set_post_tags($post_id, $tags, $append) | $append=true to keep existing tags |
| Remove all tags | wp_set_post_tags($post_id, array(), false) | Pass empty array to clear tags |
Key Takeaways
Use the Tags box in the post editor to add tags easily without code.
Use wp_set_post_tags() in PHP to add or update tags programmatically.
Set the append parameter to true to add tags without removing existing ones.
Always verify the post ID and tag spelling to avoid mistakes.
Clearing tags requires passing an empty array with append set to false.