我们正在构建一个小插件,用于向我们的网站添加自定义帖子。这些帖子具有类似类别的“属性”。这些帖子来自外部源。添加新帖子时,我们希望添加分类法(如果不存在),并为该特定帖子添加术语。我们像这样添加它(1 篇文章的示例):
$postID = 2312;
$terms = array("foo", "bar", "hello", "world");
$taxonomy = "DrivingLicense";
wp_set_object_terms($postID, $terms, $taxonomy);
此后,wp_term_taxonomy 表有 4 个条目:
term_taxonomy_id term_id taxonomy parent count
2649 2649 DrivingLicense 0 1
2650 2650 DrivingLicense 0 1
2651 2651 DrivingLicense 0 1
2652 2652 DrivingLicense 0 1
我在这里做错了什么?
我们希望只获得一种分类法“DrivingLicense”,具有由 wp_term_relationships 表链接的独特术语“foo”、“bar”、“hello”、“world”。
看起来你的 wp_set_object_terms() 方法已经差不多了,但是 WordPress 处理分类法和术语的方式有点混乱。让我们解决这个问题,让您的插件顺利运行!
了解 WordPress 分类法和术语 分类法: 这是一种分组机制,如“类别”或“标签”。在您的情况下,“驾驶执照”是分类法。
术语: 这些是分类法中的项目。例如,“foo”、“bar”、“hello”和“world”是“DrivingLicense”分类中的术语。
您当前方法的问题 当您使用 wp_set_object_terms() 时,WordPress 预计这些术语已存在于分类中。如果不这样做,WordPress 就会创建新术语。然而,WordPress 似乎将每个术语都视为新术语和新分类法,因此 wp_term_taxonomy 表中存在多个条目。
如何解决 确保分类存在:在添加术语之前,请确保您的自定义分类“DrivingLicense”已使用 register_taxonomy() 注册。这应该在插件的设置阶段完成,通常挂接到 init。
检查并添加术语:在将术语与帖子关联之前,检查它们是否存在。如果没有,请添加它们。使用 term_exists() 检查并使用 wp_insert_term() 添加新术语。
将术语与帖子关联:一旦确保术语存在,请使用 wp_set_object_terms() 将它们与您的帖子关联。
// Register taxonomy (usually in an init hook)
function register_my_taxonomy() {
register_taxonomy('DrivingLicense', 'post', /* Other args */);
}
add_action('init', 'register_my_taxonomy');
// Function to add terms to a post
function add_terms_to_post($postID, $terms, $taxonomy) {
foreach ($terms as $term) {
// Check if the term exists
if (!term_exists($term, $taxonomy)) {
// Insert the term if it doesn't exist
wp_insert_term($term, $taxonomy);
}
}
// Now associate terms with the post
wp_set_object_terms($postID, $terms, $taxonomy);
}
// Usage
$postID = 2312;
$terms = ["foo", "bar", "hello", "world"];
$taxonomy = "DrivingLicense";
add_terms_to_post($postID, $terms, $taxonomy);