Welcome to another quick article in the WordPress Development Tips Series.
During the development of my plugins, I discovered quite a few tips and tricks along the way. In this series, I try to share the most important or the ones I feel lack the most documentation.
This tip involves how to create a tag via PHP and assign it to a post.
The code is quite simple and uses just a single WordPress function, already included in the WordPress code.
How to use wp_set_object_terms()
The function to use is named wp_set_object_terms, and the usage is as follows:
<php wp_set_object_terms( $postid, $newtagarray, 'post_tag', true ); ?>
Here is a practical example
<php wp_set_object_terms( 1, array('my new tag'), 'post_tag', true ); ?>
The code in the example will create (if it doesn’t already exist) a tag named “my new tag”, and assign it to post 1.
Never miss a story or discount - sign up now