我的目标是使用某种类型的默认方法来检查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);
)
我计划将其添加为插件。任何想法或帮助都会很棒!
答案 0 :(得分:10)
你可以跑;
wp_insert_term('football', 'category', array(
'description' => 'Football Blogs',
'slug' => 'category-slug',
'parent' => 4 // must be the ID, not name
));
如果该分类已存在,该函数将不会添加该术语!
出于兴趣,您何时会在插件中调用此类代码?确保在激活钩子函数中注册它,否则它将在每次加载时运行!
更新
要通过slug获取术语的ID,请使用;
$term_ID = 0;
if ($term = get_term_by('slug', 'term_slug_name', 'taxonomy'))
$term_ID = $term->term_id;
将“分类法”替换为术语的分类 - 在您的情况下,“类别”。
答案 1 :(得分:0)
以下是分配和创建类别(如果不存在)的方法
$pid = 168; // post we will set it's categories
$cat_name = 'lova'; // category name we want to assign the post to
$taxonomy = 'category'; // category by default for posts for other custom post types like woo-commerce it is product_cat
$append = true ;// true means it will add the cateogry beside already set categories. false will overwrite
//get the category to check if exists
$cat = get_term_by('name', $cat_name , $taxonomy);
//check existence
if($cat == false){
//cateogry not exist create it
$cat = wp_insert_term($cat_name, $taxonomy);
//category id of inserted cat
$cat_id = $cat['term_id'] ;
}else{
//category already exists let's get it's id
$cat_id = $cat->term_id ;
}
//setting post category
$res=wp_set_post_terms($pid,array($cat_id),$taxonomy ,$append);
var_dump( $res );
答案 2 :(得分:0)
您好,如果该类别不存在,您也可以使用这个
//Get the categories names for every post in archive page using 'get_the_terms( ID, 'taxnomoy')'.
// Write your HTML Code/term name that you want to show if the category/term does not exist for the CPT (Custom Post Type) post
<?php $categories_name = get_the_terms( $post->ID, "postino-happening-state" );
if( $categories_name == false ) : // if caterory/term not exist ?>
// Write something...
<?php else: // if category exist ?>
// Write something...
<?php endif; ?>