Wordpress:如果不存在,则自动插入类别和标签?

use*_*297 8 wordpress wordpress-plugin

我的目标是使用某种类型的默认方法来检查Wordpress中是否存在类别,如果不存在,则添加类别.与标签相同.

这是我试图实现它的混乱:

<?php 
    if (is_term('football', 'category')) {
    } 
    else (
        $new_cat = array('cat_name' => 'Football', 'category_description' => 'Football Blogs', 'category_nicename' => 'category-slug', 'category_parent' => 'sports');
        $my_cat_id = wp_insert_category($new_cat);
    ) 
Run Code Online (Sandbox Code Playgroud)

我计划将其添加为插件.任何想法或帮助都会很棒!

The*_*dic 10

你可以跑;

wp_insert_term('football', 'category', array(
    'description' => 'Football Blogs',
    'slug' => 'category-slug',
    'parent' => 4 // must be the ID, not name
));
Run Code Online (Sandbox Code Playgroud)

如果该分类已存在,该函数将不会添加该术语!

出于兴趣,您何时会在插件中调用此类代码?确保在激活钩子函数中注册它,否则它将在每次加载时运行!

UPDATE

要通过slug获取术语的ID,请使用;

$term_ID = 0;
if ($term = get_term_by('slug', 'term_slug_name', 'taxonomy'))
    $term_ID = $term->term_id;
Run Code Online (Sandbox Code Playgroud)

将"分类法"替换为术语的分类 - 在您的情况下,"类别".