Login

WordPress: Usage of wp_set_object_terms (create relationship between objects and taxonomies)

Author:neo yang Time:2021/08/22 Read: 9930
wp_set_object_terms( int $object_id, str […]

wp_set_object_terms( int $object_id, string|int|array $terms, string $taxonomy, bool $append = false )

1. Parameters

$object_id

Object ID, such as post ID.

$terms

The main problem lies here.

If the data type is a string, the string will be used as a slug. If the term of the slug exists, a relationship between the object and the term will be created. If it does not exist, the term of the slug will be created first, and then the object and the term will be created. Relationship.

If the data type is an integer, this value will be used as the ID of the term. If the term with this ID exists, this term will be associated.

If the data type is an array, no matter what I try, I cannot create a relationship between the object and the term. So, for arrays, I use a foreach loop to create each relationship.

$taxonomy

Taxonomy slug, string.

$append

If it is false, the relationship between the original object and term will be overwritten and updated. If it is true, a new relationship is created, that is, a new term relationship is added between the object and the same taxonomy.

2. Code

foreach ($custom_terms as $key => $value) { if (is_array($value)) { foreach ($value as $k => $v) { wp_set_object_terms($postid,(int)$v,$key,true); //Same taxonomy ($key) , use true to create relationships between all terms and objects in the array. } }else{ wp_set_object_terms($postid,(int)$value,$key); //The data transmitted from the interface are all strings. In order to ensure that $value is an integer, (int) is used. } } 

3. Return

(array|WP_Error) Term taxonomy IDs of the affected terms or WP_Error on failure.

4. Summary

The parameters of many WordPress functions, like the parameters of wp_set_object_terms, can use either strings, numbers, or even arrays. However, from my own experience, in principle, if you can use digital IDs, try to use digital IDs, and if you can do without arrays, don't use arrays. In this way, some troubles will often be reduced.



copyright © www.lyustu.com all rights reserved.
Theme: TheMoon V3.0. Author:neo yang