【问题标题】:Wordpress: Insert Category & Tags Automatically if They Don't Exist?Wordpress:如果它们不存在,则自动插入类别和标签?
【发布时间】:2011-03-01 21:47:20
【问题描述】:

我的目标只是使用某种类型的默认方法来检查 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);
    ) 

我打算将其添加为插件。任何想法或帮助都会很棒!

【问题讨论】:

  • 抱歉,没有为语句输入代码:

标签: wordpress


【解决方案1】:

你可以跑;

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;

将“分类”替换为术语的分类 - 在您的情况下为“类别”。

【讨论】:

  • 伙计,有没有可能将蛞蝓用于父母?或者将使用 slug 属性的代码转过来?因为我必须手动设置代码来假设 ID 并在开头插入父项(而不是只知道 slug 名称)。
【解决方案2】:

如果不存在,这里是如何分配和创建类别

$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 );

【讨论】:

    【解决方案3】:

    你好,如果类别不存在,你也可以这样做

    //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; ?>
    

    【讨论】:

      猜你喜欢
      • 2018-09-17
      • 1970-01-01
      • 2013-05-09
      • 2012-07-12
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多