以编程方式创建类别和多个子类别

时间:2016-07-29 21:00:11

标签: php wordpress categories

此代码在wordpress管理区域中显示正确的类别。但没有显示子类别。

我需要为每个类别显示3个类别和3个子类别?

这就是我希望每个类别的内容:

A类

  • 子类别1
  • 子类别2
  • 子类别3

我在wordpress主题的functions.php文件中添加了以下代码:

//create the main category
wp_insert_term(

// the name of the category
'Category A', 

// the taxonomy, which in this case if category (don't change)
'category', 

 array(

// what to use in the url for term archive
'slug' => 'category-a',  
 ));`

然后针对每个子类别:

wp_insert_term(

// the name of the sub-category
'Sub-category 1', 

// the taxonomy 'category' (don't change)
'category',

array(
// what to use in the url for term archive
'slug' => 'sub-cat-1', 

// link with main category. In the case, become a child of the "Category A"   parent  
'parent'=> term_exists( 'Category A', 'category' )['term_id']

));

但是我收到了一个错误:

  

解析错误:解析错误,期待'')''第57行......

对应'parent'=> term_exists( 'Category A', 'category' )['term_id']

我做错了什么?

2 个答案:

答案 0 :(得分:4)

问题是您需要在函数外部获取父术语id ,以避免错误。你可以这样轻松地做到这一点:

$parent_term_a = term_exists( 'Category A', 'category' ); // array is returned if taxonomy is given
$parent_term_a_id = $parent_term_a['term_id']; // get numeric term id

// First subcategory
wp_insert_term(
    'Sub-category 1', // the term 
    'category', // the taxonomy
    array(
        // 'description'=> 'Some description.',
        'slug' => 'sub-cat-1a',
        'parent'=> $parent_term_a_id
    )
);

// Second subcategory
wp_insert_term(
    'Sub-category 2', // the term 
    'category', // the taxonomy
    array(
        // 'description'=> 'Some description.',
        'slug' => 'sub-cat-2a',
        'parent'=> $parent_term_a_id
    )
);

// Third subcategory
wp_insert_term(
    'Sub-category 3', // the term 
    'category', // the taxonomy
    array(
        // 'description'=> 'Some description.',
        'slug' => 'sub-cat-3a',
        'parent'=> $parent_term_a_id
    )
);

然后您将用于其他 2组子类别

// For subcategory group of Category B
$parent_term_b = term_exists( 'Category B', 'category' );
$parent_term_b_id = $parent_term_b['term_id'];

// For subcategory group of Category C
$parent_term_c = term_exists( 'Category C', 'category' );
$parent_term_c_id = $parent_term_c['term_id'];

......以同样的方式(注意每个子类别一个独特的slug ,这意味着所有9个不同的子类别slu) ......

参考:

答案 1 :(得分:1)

看起来您错过了父类别名称中的第一个引用,并且可以解释解析错误,该错误应该是:

         $(".replies_show").click (function(e){
            $(".replies_show").replaceWith(" ");
            $(this).next(".replies").show();
            e.preventDefault();
        });

编辑评论:

// the name of the category
'Category A', 
相关问题