Creating Wordpress Category at the time of Theme Activation

心不动则不痛 提交于 2019-12-08 04:27:57

问题


I am going to create a function that will check whether if a Category named Testimonials is already available or not. If it is available do noting, whereas if it is not there, then create a new Category named Testimonials. I am using following code but nothing happened at the time of theme activation. What is missing?

function create_my_cat () {
    if (file_exists (ABSPATH.'/wp-admin/includes/taxonomy.php')) {
        require_once (ABSPATH.'/wp-admin/includes/taxonomy.php');    
        if (!get_cat_ID('testimonials')) {
            wp_create_category('testimonials');
        }
    }
}
add_action ('create_category', 'create_my_cat');

回答1:


The action create_category runs when a new category is created.

You want your category creation function to run when the theme is activated. The relevant action is after_setup_theme.

Drop this in your theme's functions.php and you should be good to go:

function create_my_cat () {
    if (file_exists (ABSPATH.'/wp-admin/includes/taxonomy.php')) {
        require_once (ABSPATH.'/wp-admin/includes/taxonomy.php'); 
        if ( ! get_cat_ID( 'Testimonials' ) ) {
            wp_create_category( 'Testimonials' );
        }
    }
}
add_action ( 'after_setup_theme', 'create_my_cat' );



回答2:


Note: If you have already used a function my_theme_name_setup() {} you don't need another function. One more *note to mention; you can also use category_exists instead of get_cat_ID(), so the full code example is:

function my_theme_name_setup() {

    if( file_exists( ABSPATH . '/wp-admin/includes/taxonomy.php' ) ) :
        require_once( ABSPATH . '/wp-admin/includes/taxonomy.php' );

            if( ! category_exists( 'name' ) ) :

                wp_create_category( 'name' );

            endif;// Category exists

    endif;// File exists 

}
add_action( 'after_setup_theme', 'my_theme_name_setup' );


来源:https://stackoverflow.com/questions/8389387/creating-wordpress-category-at-the-time-of-theme-activation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!